I have below class defined to do statistics for voting system.
class FormPage(AbstractForm):
submission_stats = models.JSONField(null=True, editable=False)
Now, I have submission_stats in below format:
[
{
"id":4,
"label":"checkboxes",
"choices":[
{
"content":"option-A",
"num_vote":0,
"user_list":[
]
},
{
"content":"option-B",
"num_vote":0,
"user_list":[
]
},
{
"content":"option-C",
"num_vote":0,
"user_list":[
]
}
]
},
{
"id":7,
"label":"Radio Button",
"choices":[
{
"content":"option-1",
"num_vote":0,
"user_list":[
]
},
{
"content":"option-2",
"num_vote":0,
"user_list":[
]
},
{
"content":"option-3",
"num_vote":0,
"user_list":[
]
}
]
}
]
When I receive 2 vote submissions for example, I want to update num_vote (from 0 to 2) and user_list (from [] to [user_a, user_b]) field in this JSONField accordingly.
How to query and update elements in nested JSONField data please ?
install json library
pip install json
import json
data = json.load(submission_stats)
now this data is python dictionary. update it however you want
to save updated data back to json field, convert dictionary back to json like this
json.dumps(data, indent = 4)
and save
plus if you want to use sql with your this project i highly recomment you use
from django_extensions.db.fields.json import JSONField
instead of
models.JSONField
because models.JSONField doesn't go well with SQL
Related
I'm using MongoDB Compass to export my data as csv file, but I have only the choice to select which field I want and not elements in a specific field.
MongoDB export data:
Actually, I'm interested to save only the "scores" for object "0,1,2".
Here a ScreenShot from MongDB Compas:
It is something that I should deal with python?
One option could be to "rewrite" "scoreTable" so that there are a maximum of 3 elements in the "scores" array and then "$out" to a new collection that can be exported in full.
db.devicescores.aggregate([
{
"$set": {
"scoreTable": {
"$map": {
"input": "$scoreTable",
"as": "player",
"in": {
"$mergeObjects": [
"$$player",
{"scores": {"$slice": ["$$player.scores", 3]}}
]
}
}
}
}
},
{"$out": "outCollection"}
])
Try it on mongoplayground.net.
I have few items in DynamoDB like this.
Example 1 -
{
"policyName":"Some Name",
"domainBypassList":{
"custom":[],
"default":[]
}
"applicationBypassList":{
"default":{
"Mac":[],
"Windows":[]
},
"custom":{
"Mac":[],
"Window":[]
}
}
Example 2 -
{
"policyName":"Some Name",
"domainBypassList":{
"default":[]
}
"applicationBypassList":{
"default":{
"Mac":[],
"Windows":[]
}
}
I want to add/update the custom of domainBypassList & applicationBypassList. You can see in Example 1 the custom attribute exist in both domainBypassList & applicationBypassList. However, in Example 2 you can see that custom attribute is missing. So if the custom attribute is missing then it should be added or if it exist then it should be updated.
I wrote a simple query which works only if the custom attribute exist in both domainBypassList & applicationBypassList i.e Example 1.
res = self.service_context.policies.update_item(
Key={
'tenantId': self.event["user"]['tenantId'],
'policyName': self.policy_name
},
UpdateExpression="set domainBypassList.custom=:dbl, applicationBypassList.custom=:abl, updatedAt=:uat",
ExpressionAttributeValues={
':abl': self.payload["applicationBypassList"],
':dbl': self.payload["domainBypassList"],
':uat': datetime.datetime.now().strftime("%Y/%m/%d, %I:%M %p")
},
ReturnValues="UPDATED_NEW"
)
How can I make this query make work with both the cases.
Here is the object that I have for custom of both domainBypassList & applicationBypassList.
{
"applicationBypassList":{
"Mac": [
"Zoom.us",
"fool.is"
],
"Windows": [
"Zoom.exe",
"cool.com"
]
},
"domainBypassList":["some.com"]
}
For example, if this is my record
{
"_id":"123",
"name":"google",
"ip_1":"10.0.0.1",
"ip_2":"10.0.0.2",
"ip_3":"10.0.1",
"ip_4":"10.0.1",
"description":""}
I want to get only those fields starting with 'ip_'. Consider I have 500 fields & only 15 of them start with 'ip_'
Can we do something like this to get the output -
db.collection.find({id:"123"}, {'ip*':1})
Output -
{
"ip_1":"10.0.0.1",
"ip_2":"10.0.0.2",
"ip_3":"10.0.1",
"ip_4":"10.0.1"
}
The following aggregate query, using PyMongo, returns documents with the field names starting with "ip_".
Note the various aggregation operators used: $filter, $regexMatch, $objectToArray, $arrayToObject. The aggregation pipeline the two stages $project and $replaceWith.
pipeline = [
{
"$project": {
"ipFields": {
"$filter" : {
"input": { "$objectToArray": "$$ROOT" },
"cond": { "$regexMatch": { "input": "$$this.k" , "regex": "^ip" } }
}
}
}
},
{
"$replaceWith": { "$arrayToObject": "$ipFields" }
}
]
pprint.pprint(list(collection.aggregate(pipeline)))
I am unaware of a way to specify an expression that would decide which hash keys would be projected. MongoDB has projection operators but they deal with arrays and text search.
If you have a fixed possible set of ip fields, you can simply request all of them regardless of which fields are present in a particular document, e.g. project with
{ip_1: true, ip_2: true, ...}
I am new to the JSON python lib.
I have this JSON file:
{
"usrdata": [
{
"user": "---/ LandiPlayz \\---#****",
"money": 10
},
{
"user": "Snubz#****",
"money": 10
}
]
}
and I need to modify the "money" field of one of the users. There will be more added users, so I need to find which one it is by finding the users name. Is that possible, or should I do format the file differently.
Thanks in advance
You have to iterate over the user_infos, and when getting the good one, update the money
json_value = {
"usrdata": [
{"user": "---/ LandiPlayz \\---#****","money": 10},
{"user": "Snubz#****","money": 10}
]
}
username = "Snubz#****"
new_money = 50
for user_info in json_value["usrdata"]:
if user_info['user'] == username:
user_info['money'] = new_money
so I want to get the first key element from this JSON using python 3.7 without knowing its name.
Here is the JSON:
{
"intent":[
{
"confidence":0.99313362101529,
"value":"sendmessage"
}
],
"wikipedia_search_query":[
{
"suggested":true,
"confidence":0.93804001808167,
"value":"message",
"type":"value"
}
],
"messenger_recipient":[
{
"confidence":0.93138399364195,
"value":"me",
"type":"value"
}
]
}
EDIT:
I want to compare the name of the first key like so:
if(jsonobj[0] == "wikipedia_search_query")
dosomething()
While Python 3.6+ does maintain insertion order on dictionaries, there's no guarantee that your incoming JSON will be in the order you expect. That being said, if you can guarantee the insertion order, here's a working example.
import json
js = """{
"intent":[
{
"confidence":0.99313362101529,
"value":"sendmessage"
}
],
"wikipedia_search_query":[
{
"suggested":true,
"confidence":0.93804001808167,
"value":"message",
"type":"value"
}
],
"messenger_recipient":[
{
"confidence":0.93138399364195,
"value":"me",
"type":"value"
}
]
}"""
json_data = json.loads(js)
first_key = next(iter(json_data))
first_value = json_data[next(iter(json_data))]
print(first_key)
print(first_value)
Output
intent
[{'confidence': 0.99313362101529, 'value': 'sendmessage'}]