I have a Following Json File format in which the data will be having Dynamic update.
I have to parse the Json file using python with the following scenario
If the status: "PASS", then the results of value should be maths,q1 ,q2
Kindly me with this scenario using python
{
"quiz": {
"sport": {
"q1": {
"question": "Which one is correct team name in NBA?",
"options": [
"New York Bulls",
"Los Angeles Kings",
"Golden State Warriros",
"Huston Rocket"
],
"answer": "Huston Rocket"
},
"status": "BLOCK"
},
"maths": {
"q1": {
"question": "5 + 7 = ?",
"options": [
"10",
"11",
"12",
"13"
],
"answer": "12"
},
"q2": {
"question": "12 - 8 = ?",
"options": [
"1",
"2",
"3",
"4"
],
"answer": "4"
},
"status": "PASS"
}
}
}
Hope below code gives you the expected output
import json
file = open('data.json')
data = json.load(file)
keys = []
for i in data['quiz']:
if data['quiz'][i]['status'] != 'PASS':
keys.append(i)
for key in keys:
del data['quiz'][key]
print(data)
for key in data['quiz'].keys():
print(key)
for key1 in data['quiz'][key].keys():
if key1 != 'status':
print(key1)
Related
I have some JSON data like:
[
{
"adset_id": "23851149362570451",
"reach": "862",
"clicks": "1",
"actions": [
{
"action_type": "post_reaction",
"value": "1"
},
{
"action_type": "post_engagement",
"value": "1"
},
{
"action_type": "page_engagement",
"value": "1"
}
],
"date_start": "2022-10-06",
},
]
In the actual data, this array would contain around 30 or 40 objects; I have shown just one for reference.
How can I flatten everything inside the "actions" array, so that it looks like this instead?
[
{
"adset_id": "23851149362570451",
"reach": "862",
"clicks": "1",
"post_reaction" : "1",
"post_engagement" : "1",
"page_engagement" : "1",
"date_start": "2022-10-06",
},
]
I quickly wrote this. Modify it as per how you ingest the data:
import json
final_result = []
with open('data.json') as f:
api_data_dict = json.load(f)
for api_data_obj in api_data_dict:
actions = []
values = []
updated_actions = {}
#assuming there are objects with action_type and value present inside this dict
for action in api_data_obj['actions']:
actions.append(action['action_type'])
values.append(action['value'])
for action, value in zip(actions, values):
updated_actions[action] = value
api_data_obj.pop('actions', None)
final_result.append({**api_data_obj, **updated_actions})
print(final_result)
data.json contents:
[{
"adset_id": "23851149362570451",
"reach": "862",
"clicks": "1",
"actions": [
{
"action_type": "post_reaction",
"value": "1"
},
{
"action_type": "post_engagement",
"value": "1"
},
{
"action_type": "page_engagement",
"value": "1"
}
],
"date_start": "2022-10-06"
},
{
"adset_id": "234543535643543",
"reach": "862",
"clicks": "1",
"actions": [
{
"action_type": "post_reaction",
"value": "2"
},
{
"action_type": "post_engagement",
"value": "2"
},
{
"action_type": "page_engagement",
"value": "2"
}
],
"date_start": "2022-10-06"
}]
Result:
[
{
"adset_id":"23851149362570451",
"reach":"862",
"clicks":"1",
"date_start":"2022-10-06",
"post_reaction":"1",
"post_engagement":"1",
"page_engagement":"1"
},
{
"adset_id":"234543535643543",
"reach":"862",
"clicks":"1",
"date_start":"2022-10-06",
"post_reaction":"2",
"post_engagement":"2",
"page_engagement":"2"
}
]
So, I have JSON data that I am getting from an HTML form. I have to format this data to have a specific JSON structure as shown below.
[
{
"Header": "Stats",
"Line_01": "Line 01",
"Line_02": "Line 02",
"Line_03": "Line 03",
"Line_04": "Line 04",
"Line_05": "Line 05",
"Line_06": "Line 06",
"Line_07": "Line 07"
},
{
"Header": "JUV",
"Line_01": "89",
"Line_02": "34",
"Line_03": "765",
"Line_04": "123",
"Line_05": "1",
"Line_06": "4",
"Line_07": "455"
},
{
"Header": "SMP",
"Line_01": "12",
"Line_02": "89",
"Line_03": "124",
"Line_04": "678",
"Line_05": "92",
"Line_06": "120",
"Line_07": "5"
}
]
JSON I have from the HTML form is:
[
{
"name": "00",
"value": "JUV"
},
{
"name": "00",
"value": "STATS"
},
{
"name": "00",
"value": "SMP"
},
{
"name": "00",
"value": "89"
},
{
"name": "01",
"value": "LINE 01"
},
{
"name": "02",
"value": "12"
},
{
"name": "03",
"value": "34"
},
{
"name": "04",
"value": "LINE 02"
},
{
"name": "05",
"value": "89"
},
{
"name": "06",
"value": "765"
},
{
"name": "07",
"value": "LINE 03"
},
{
"name": "08",
"value": "124"
},
{
"name": "09",
"value": "123"
},
{
"name": "10",
"value": "LINE 04"
},
{
"name": "11",
"value": "678"
},
{
"name": "12",
"value": "1"
},
{
"name": "13",
"value": "LINE 05"
},
{
"name": "14",
"value": "92"
},
{
"name": "15",
"value": "4"
},
{
"name": "16",
"value": "LINE 06"
},
{
"name": "17",
"value": "120"
},
{
"name": "18",
"value": "455"
},
{
"name": "19",
"value": "LINE 07"
},
{
"name": "20",
"value": "5"
}
]
The form looks like this: HTML form - Image on Pasteboard
The Python code I am trying so far is:
import json
jarr = []
final_file = {}
json_template = {
"Header": "",
"Line_01": "",
"Line_02": "",
"Line_03": "",
"Line_04": "",
"Line_05": "",
"Line_06": "",
"Line_07": ""
}
with open("testo101.json",) as f:
jdata = json.load(f)
k = 0
for i in range(8):
a =[]
for j in range(3):
a.append(jdata[k]['value'])
k+=1
jarr.append(a)
for i, x in enumerate(json_template):
json_template[x]=jarr[i][1]
final_file.update(json_template)
for i, x in enumerate(json_template):
json_template[x]=jarr[i][0]
final_file.update(json_template)
for i, x in enumerate(json_template):
json_template[x]=jarr[i][2]
final_file.update(json_template)
print(final_file)
So what I have done so far is:
Import the JSON file I got from HTML form.
Covert it into a 3x8 matrix... so I can get values of each column
easily.
I can fill values from the JSON in the json_template dictionary with
the help of 2D array I just created.
The Problem:
I can't figure out how to merge the 3 dictionaries that I am generating from each column of the 2D array into a single dictionary final_file so I can dump it as a JSON file and that's what I want. How can I do this... or if there is some other better way to do this then please help.
Thanks.
These code should do the job:
import json
jarr = []
final_file = [] # CHANGE #1
json_template = {
"Header": "",
"Line_01": "",
"Line_02": "",
"Line_03": "",
"Line_04": "",
"Line_05": "",
"Line_06": "",
"Line_07": ""
}
with open("testo101.json",) as f:
jdata = json.load(f)
k = 0
for i in range(8):
a =[]
for j in range(3):
a.append(jdata[k]['value'])
k+=1
jarr.append(a)
for i, x in enumerate(json_template):
json_template[x]=jarr[i][1]
final_file.append(json_template.copy()) # CHANGE #2
for i, x in enumerate(json_template):
json_template[x]=jarr[i][0]
final_file.append(json_template.copy()) # CHANGE #2
for i, x in enumerate(json_template):
json_template[x]=jarr[i][2]
final_file.append(json_template.copy()) # CHANGE #2
with open('yourjson.json', 'w') as jsonfile:
json.dump(final_file, jsonfile, indent=4)
I made two changes to your code:
You need a list of dictionaries, not just one dictionary to dump three dictionaries, so I changed final_file to a list.
After you make each json_template, I attached a copy of the template to the list. (.copy() is important, otherwise later changes will be reflected in the previous entries and you end up getting three of the same item).
I wrote the dumping code and attached it to the end. You can open yourjson.json to see the result.
I have a list of dictionaries, in which I'm trying to make the value of key 'Username' as the key in a new dictionary, and subsequent key-value pairs as a dictionary value to the 'Username' key in the new dictionary.
One of the checks involves returning the first element from the list if the GECOS value is a list, otherwise return the string value of the GECOS key.
For the first two dictionaries, I'm not able to get the entire string.
I have the data below:
test_list = [
{
"Username": "root",
"UID": "0",
"GECOS": "root",
"Group List": [
""
]
},
{
"Username": "daemon",
"UID": "1",
"GECOS": "daemon",
"Group List": [
""
]
},
{
"Username": "hplip",
"UID": "118",
"GECOS": [
"HPLIP system user",
"",
"",
""
],
"Group List": [
""
]
},
{
"Username": "speech-dispatcher",
"UID": "111",
"GECOS": [
"Speech Dispatcher",
"",
"",
""
],
"Group List": [
"pulse",
"test"
]
}
]
and the following code:
import json
new_dict = {}
for dict_item in test_list:
for key in dict_item:
new_dict[dict_item["Username"]] = {
'UID'.title().lower(): dict_item['UID'],
'GECOS'.title(): dict_item['GECOS'][0] if isinstance(dict_item[key], list) else dict_item['GECOS'],
'Group List'.title(): [] if all('' == s or s.isspace() for s in dict_item['Group List']) else dict_item['Group List']
}
print(json.dumps(new_dict, indent=4))
The output of this is:
{
"root": {
"uid": "0",
"Gecos": "r",
"Group List": []
},
"daemon": {
"uid": "1",
"Gecos": "d",
"Group List": []
},
"hplip": {
"uid": "118",
"Gecos": "HPLIP system user",
"Group List": []
},
"speech-dispatcher": {
"uid": "111",
"Gecos": "Speech Dispatcher",
"Group List": [
"pulse",
"test"
]
}
}
And the expected output is:
{
"root": {
"uid": "0",
"Gecos": "root",
"Group List": []
},
"daemon": {
"uid": "1",
"Gecos": "daemon",
"Group List": []
},
"hplip": {
"uid": "118",
"Gecos": "HPLIP system user",
"Group List": []
},
"speech-dispatcher": {
"uid": "111",
"Gecos": "Speech Dispatcher",
"Group List": [
"pulse",
"test"
]
}
}
You should not iterate through the keys of each dict. Instead, access the keys directly, as a dict should:
import json
new_dict = {}
for dict_item in test_list:
new_dict[dict_item["Username"]] = {
'UID'.title().lower(): dict_item['UID'],
'GECOS'.title(): dict_item['GECOS'][0] if isinstance(dict_item['GECOS'], list) else dict_item['GECOS'],
'Group List'.title(): [] if all('' == s or s.isspace() for s in dict_item['Group List']) else dict_item['Group List']
}
print(json.dumps(new_dict, indent=4))
I have json file i what to read all the values
data=""" {"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}
{
"maps":[
{"id":"apple","iscategorical":"0"},
{"id":"ball","iscategorical":"0"}
],
"mask":{"id1":"aaaaa"},
"mask":{"id1":"bbb"},
"mask":{"id1":"cccccc"},
"om_points":"value",
"parameters":
{"id":"valore"}
}"""
out = json.loads(data)
how to get all values
firstname
lastname
mask.id1
map.id
output:
[(firstname_vaues,lastname_values,mask.id1,map.id)
(firstname_vaues,lastname_values,mask.id1,map.id) ......]
please help me
First thing, there are two json objects in your data string. So you cannot use json.loads(data). You can seperate them by a charcter like ";" . Then split the string and use json.loads on each of them.Use following code.
import json
data=""" {
"employees": [{
"firstName": "John",
"lastName": "Doe"
}, {
"firstName": "Anna",
"lastName": "Smith"
}, {
"firstName": "Peter",
"lastName": "Jones"
}]
};{
"maps": [{
"id": "apple",
"iscategorical": "0"
}, {
"id": "ball",
"iscategorical": "0"
}],
"mask": {
"id1": "aaaaa"
},
"mask": {
"id1": "bbb"
},
"mask": {
"id1": "cccccc"
},
"om_points": "value",
"parameters": {
"id": "valore"
}
}"""
splitdata = data.split(';')
datatop = json.loads(splitdata[0])
databottom = json.loads(splitdata[1])
Then you can access required fields as follows
print(datatop['employees'][0]['firstName'])
print(datatop['employees'][0]['lastName'])
print(databottom['mask']['id1'])
print(databottom['maps'][0]['id'])
Assuming I have the following JSON Object:
{
"type": "Bands",
"Artists": [{
"profile": {
"name":"Marissa"
"age": "7"
"hobbies": [{
"name":"Skiing",
"experience": "1 year"
}]
},
"popularsong":{
"name":"Wishing on a Star"
"year": 2007
}
},
{
"profile": {
"name":"Kelsey"
"age": "7"
"hobbies": [{
"name":"Piano",
"experience": "1 year"
}]
}
"popularsong":{
"name":"The Twinkle"
"year": 2007
}
},...
]
}
Assuming this json is loaded into a dictionary with json.loads(json_string)
What is the most efficient means of searching for all "Artist" entries with "age" of "7" and sticking them into an array or another dictionary?
Note that an artist entry is comprised of both the "profile" and the "popular song" something like:
{
"profile": {
"name":"Marissa"
"age": "7"
"hobbies": [{
"name":"Skiing",
"experience": "1 year"
},
"popularsong":{
"name":"The Twinkle"
"year": 2007
}
[artist for artist in myJson['Artists'] if artist['profile']['age'] == 7] might work, if I'm mentally parsing that JSON correctly.