I'm trying to search a JSON Object and extract the Key/Value pairs for 'name' and 'id' below. I would like to extract all instances of the 'name' and 'id':
{
"response": [
{
"additionalInfo": [],
"id": "b6549916-b8e1-4131-b0be-f4a3daee26fc",
"instanceTenantId": "5ffc97db91d68700c7ea827a",
"name": "Global",
"siteHierarchy": "b6549916-a8e1-4131-b0be-f4a3daee26fc",
"siteNameHierarchy": "Global"
},
{
"additionalInfo": [
{
"attributes": {
"addressInheritedFrom": "66284774-4ae4-42a1-b27c-68231c98d7db",
"type": "area"
},
"nameSpace": "Location"
}
],
"id": "4ffb292c-4cc8-444b-8978-61b97c6874db",
"instanceTenantId": "5ffc97db91d68700c7ea827a",
"name": "Peak Tester",
"parentId": "66a84774-4ae4-42a1-b27c-68231c98d7db",
"siteHierarchy": "b6549916-b8e1-4131-b0be-f4a3daee21fc/66a84774-4ae4-42a1-b27c-68231c98d7db/4ffb292c-4cc8-444b-8978-61b97c6874db",
"siteNameHierarchy": "Global/Template Site/Peak Tester"
}
]
}
I have tried several things that are not working.
for elements in site_info['response']:
for item in elements:
if item == 'name':
print(item)
This only prints the output of 'name' and not the value. I would like the value as well as the key.
Simply when you have the key and you need the value, you have to do this:
>>> dictionary['key']
'value'
In your case:
if item == 'name':
print(item['name'])
Anyway you can simply omitt the if statement this way:
for item in elements:
print(item['name'])
I see you already have your answer, which is great.
data = { "response": [ {"name" : "fred"}, {"name" : "tom"}]} # data is a dictionary
arr = data['response'] # arr is a list of dictionaries
for i in arr:
print('name', i['name']) # lookup the name value from each sub-dictionary
Related
I have a dict like below with hundreds of "assets". I would like to get the key="href" and print the url but because all "assets" are in a list and the first key of "assets" is changing I havent found a way to get there. Thanks for helping!
d = {"features": [
{
"assets": {
"swissbuildings3d_2_2018-07_1064-24_2056_5728.dxf.zip": {
"checksum:multihash":
"1220A94A04BD19E190139FAD49E6174DE82987221F7330DDEB7F6943AEAC3D7C4C78",
"created": "2021-02-10T17:51:31.618859Z",
"href":
"https://data.geo.admin.ch/ch.swisstopo.swissbuildings3d_2/swissbuildings3d_2_2018-07_1064-24/swissbuildings3d_2_2018-07_1064-24_2056_5728.dxf.zip",
"proj:epsg": 2056,
"type": "application/x.dxf+zip",
"updated": "2021-02-10T17:51:31.618877Z"
}
}
},
{
"assets": {
"swissbuildings3d_2_2018-07_1064-42_2056_5728.dxf.zip": {
"checksum:multihash":
"1220EA3AFCCDE8648CB60CDF17AF679458233DE2E6052CBBB91F058CBCA651191F6D",
"created": "2021-02-10T17:51:33.722985Z",
"href":
"https://data.geo.admin.ch/ch.swisstopo.swissbuildings3d_2/swissbuildings3d_2_2018-07_1064-42/swissbuildings3d_2_2018-07_1064-42_2056_5728.dxf.zip",
"proj:epsg": 2056,
"type": "application/x.dxf+zip",
"updated": "2021-02-10T17:51:33.723005Z"}
}
}
]}
Try this one.
output_list = []
for data_dict in d['features']:
for key, value_dict in data_dict['assets'].items():
output_list.append(value_dict['href'])
print(output_list)
Output:
['https://data.geo.admin.ch/ch.swisstopo.swissbuildings3d_2/swissbuildings3d_2_2018-07_1064-24/swissbuildings3d_2_2018-07_1064-24_2056_5728.dxf.zip', 'https://data.geo.admin.ch/ch.swisstopo.swissbuildings3d_2/swissbuildings3d_2_2018-07_1064-42/swissbuildings3d_2_2018-07_1064-42_2056_5728.dxf.zip']
If the dictionary in your example is assigned to a variable called d, this works:
result = [(next(iter(x['assets'])), x['assets'][next(iter(x['assets']))]['href']) for x in d['features']]
print(result)
Output:
[('swissbuildings3d_2_2018-07_1064-24_2056_5728.dxf.zip', 'https://data.geo.admin.ch/ch.swisstopo.swissbuildings3d_2/swissbuildings3d_2_2018-07_1064-24/swissbuildings3d_2_2018-07_1064-24_2056_5728.dxf.zip'), ('swissbuildings3d_2_2018-07_1064-42_2056_5728.dxf.zip', 'https://data.geo.admin.ch/ch.swisstopo.swissbuildings3d_2/swissbuildings3d_2_2018-07_1064-42/swissbuildings3d_2_2018-07_1064-42_2056_5728.dxf.zip')]
If what you shared wasn't in fact a dictionary, but a .json file, this is how to get it all the same:
import json
with open('mydata.json') as f:
d = load.loads(f.read())
For below content how can I get "a_id" value and its "b_id" value based on "name" validation.
[
{
"name": "name1",
"a_id": "12345",
"b_id": "0d687c94c5f4"
},
{
"name": "name2",
"a_id": "67890",
"b_id": "0d687c94c5f4"
},
{
"name": "name3",
"a_id": "23857",
"b_id": "9ec34be3d535"
},
{
"name": "name4",
"a_id": "84596",
"b_id": "9ec34be3d535"
},
{
"name": "name5",
"a_id": "d82ebe9815cc",
"b_id": null
}
]
I have used for two values like
{result['a_id']: result['name'] for result in data}
but for third value it won't let me do this if I use like this.
{result['a_id']: result['name'], result['b_id']: result['name'] for result in data}
what is the correct syntax.
I think a dict comprehension with a nested loop should do the trick:
data = {result[k] : result['name'] for result in data for k in ('a_id', 'b_id')}
You can add as many keys as you want. If it makes more sense, declare your keys outside, in a variable keys:
keys = ('a_id', 'b_id', ...)
data = {result[k] : result['name'] for result in data for k in keys}
Trying to grab certain values from a json file and then 're-create' a new json file (sort of like a conversion). In the code below. I do the following:
define function that returns an dictionary
for each item in json, if function returns results, add results to list located inside parentObj dictionary
oldFile.json:
{
"elements": [
{
"fieldValues": [
{
"id": "101",
"value": "John"
},
{
"id": "102",
"value": "Doe"
}
]
},
{
"fieldValues": [
{
"id": "101",
"value": "Jane"
},
{
"id": "102",
"value": "Doe"
}
]
}
]
}
file.py
import json
import os
output = {}
parentObj = {}
parentObj['entries'] = []
def grabVals(iCounter):
# legend is a pre-determined dictionary matching ids with names (like first/last)
for myKey in subResults['elements'][iCounter]['fieldValues']:
if myKey['id'] in legend:
if 'value' in myKey:
newEntry = {legend[myKey['id']]: myKey['value']}
output.update(newEntry) # first adds 'John', then 'Doe'
# sample output below; next iteration would be 'Jane Doe'
# {"First": "John", "Last": "Doe"}
return output
subResults = json.loads(oldFile.json)
formCount = len(subResults['elements']) # subResults is the json above file. Grab total number of entries
for counter in range(0, formCount):
if convertTime(formEntryStamp, formEntryID) == 'keep': # self defined function (returns keep or None)
parentObj['entries'].append(grabVals(counter))
else:
pass
export = json.dumps(parent_obj, indent=4, sort_keys=False) # create new json based of dictionary
f = open("finished.json", "w")
f.write(export)
f.close()
Expected data in finished.json
{
"entries": [
{
"First": "John",
"Last": "Doe"
},
{
"First": "Jane",
"Last": "Doe"
}
]
}
Actual data in finished.json:
{
"entries": [
{
"First": "Jane",
"Last": "Doe"
},
{
"First": "Jane",
"Last": "Doe"
}
]
}
My question: How do I permanently write to parentObj? When output is changed in the function, the value inside parentObj is overwritten with new value. Does this have something to do mututable/immutable objects? Please let me know any further clarification is required.
Related links are similar, but refer to lists, whereas my is an object/dictionary:
Link 1
Link 2
After doing some reading on mutation of objects in python (link here), the code below solved my problem. Similar to what Juanpa said in the comments, I mutated the variable that was being re-used in my function (output). I assume with the code below, I am creating a copy thus leaving the original untouched.
def grabVals(iCounter, output=None):
if output == None:
output = {}
for myKey in subResults['elements'][iCounter]['fieldValues']:
if myKey['id'] in legend:
if 'value' in myKey:
newEntry = {legend[myKey['id']]: myKey['value']}
output.update(newEntry)
return output
I am using django rest framework to returned response in json format for jquery.
I have a dictionary object which contains another dictionary object:
items = {
['name':'Chairs','options':{'type':'office','price':100}],
['name':'Tables','options':{'type':'office','price':45}],
}
response = Response( json.dumps(output_items) , status=status.HTTP_200_OK)
On JavaScript side I am using this code:
var array = JSON.parse(json);
that is not parsing JSON, that is creating errors.
I want to create this json format:
{
"1": {
"name": "Chairs",
"description": "All chairs",
"options": {
"1":{"type": "Office", "price": 130 },
"2":{"type": "Home", "price": 75 },
"3":{"type": "Shop", "price": 100 }
}
},
"2": {
"name": "Tables",
"description": "table description",
"options": {
"1":{"type": "Office", "price": 240 },
"2":{"type": "Home", "price": 200 },
"3":{"type": "Shop", "price": 180 }
}
}
}
I stored all my data using python dictionary and list objects , how can i create this format json output string from dictionaries data?
This is not a proper json or Python object. Python Lists cannot take named arguments. Only a dictionary can take key, value pairs. If you wish to go for a list, it has to be dictionaries added to the list and not as key value pairs. The items should be something like this:
List of dictionaries
items = [
{"name":"Chairs","options":{"type":"office","price":100}},
{"name":"Tables","options":{"type":"office","price":45}},
]
(or)
Dictionary of dictionaries
items = {
"first":{"name":"Chairs","options":{"type":"office","price":100}},
"second":{"name":"Tables","options":{"type":"office","price":45}}
}
You have an error in you object "items". Try this one
items = [
{'name':'Chairs','options':{'type':'office','price':100}},
{'name':'Tables','options':{'type':'office','price':45}},
]
You have an error in dict creation ['name':'Chairs','options':{'type':'office','price':100}] This is not a pair of key: value
you are not doing it correctly as mentioned by others, you can test it in your browser's console just type in
x={'type':'office','price':100}
//Object {type: "office", price: 100}
y={'type':'office','price':45}
//Object {type: "office", price: 45}
opt1={'type':x}
//Object {type: Object}
opt2={'type':y}
//Object {type: Object}
val1={'name':'Chairs', 'options':opt1}
//Object {name: "Chairs", options: Object}
val2={name:'tables','options':opt2}
//Object {name: "tables", options: Object}
items={'1':val1,'2':val2}
you will have the needed format for your data and you will get an idea about how to formulate the data too. hope it helps
My JSON data is in this format..
[
{
"id": "532befe4ee434047ff968a6e",
"company": "528458c4bbe7823947b6d2a3",
"values" : [
{
"Value":"11",
"uniqueId":true
},
{
"Value":"14",
"uniqueId":true
},
]
},
{
"id": "532befe4ee434047ff968a",
"company": "528458c4bbe7823947b6d",
"values" : [
{
"Value":"1111",
"uniqueId":true
},
{
"Value":"10",
"uniqueId":true
},
]
}
]
If I want to filter based on company field then it is possible in this way.
qaresults = QAResult.objects.filter(company= comapnyId)
and it gives me first dictionary of list
But what If I want to filter this based on values list's "value" of Value Key of first dictionary ?
I am not 100% sure what you want , but from what i understand your question,
Try this solution :
import json
json_dict = json.loads('[{"id": "532befe4ee434047ff968a6e","company": "528458c4bbe7823947b6d2a3","values": [{"Value": "11","uniqueId": true},{"Value": "14","uniqueId": true}]},{"id": "532befe4ee434047ff968a","company": "528458c4bbe7823947b6d","values": [{"Value": "1111","uniqueId": true},{"Value": "10","uniqueId": true}]}]')
expected_values = []
js = json_dict[0]
for key,value in js.items():
if key == 'values':
expected_values.append(value[0]['Value'])
And then
qaresults = QAResult.objects.filter(company__id__in = expected_values)