How to access elements in a specific way in json? - python

I want to learn JSON and I am using Python. I currently have a question about how to access elements. Here would be a generic example of the JSON information:
"data":{
"Bob":{
"name":"Bob",
"age":"30",
"state":"California",
"job":"accountant"
},
"Joe":{
"name":"Bob",
"age":"30",
"state":"Florida",
"job":"engineer"
},
"Tom":{
"name":"Bob",
"age":"25",
"state":"North Dakota",
"job":"manager"
}
}
Now, I would want to make a for loop that gets a list of all the names that are age 30. How am I going to do this. I tried doing something like this:
array = []
for x in range(0,3):
if data[x]['age'] is '30'
array.append(data[x])
but that is definitely wrong. Can somebody teach me how to sort the items in JSON in this way?

You can iterate via JSON data the same as via Python dict
import json
with open('data.json') as json_file:
input_data = json.load(json_file)
data = []
# use dict function items that iterate via key, value in our cause k - key, v - value
for k, v in input_data['data'].items():
if v['age'] == '30':
data.append(v)
print(data)
Output:
[{'name': 'Bob', 'age': '30', 'state': 'California', 'job': 'accountant'}, {'name': 'Bob', 'age': '30', 'state': 'Florida', 'job': 'engineer'}]

Try this:
data = {
"Bob":{
"name":"Bob",
"age":"30",
"state":"California",
"job":"accountant"
},
"Joe":{
"name":"Bob",
"age":"30",
"state":"Florida",
"job":"engineer"
},
"Tom":{
"name":"Bob",
"age":"25",
"state":"North Dakota",
"job":"manager"
}
}
names = []
for name, information in data.items():
if information['age'] == '30':
names.append(name)
print(names)
If you have a dictionary object called data, you can use data.items() to iterate over the keys ('Bob', 'Joe', 'Tom') and values of the dictionary. You could check out the documentation here: https://docs.python.org/3/library/stdtypes.html#dict.items

json_data = {"data":{
"Bob":{
"name":"Bob",
"age":"30",
"state":"California",
"job":"accountant"
},
"Joe":{
"name":"Bob",
"age":"30",
"state":"Florida",
"job":"engineer"
},
"Tom":{
"name":"Bob",
"age":"25",
"state":"North Dakota",
"job":"manager"
}
}
}
names = []
for k, v in json_data['data'].items():
if v['age'] == '30':
names.append(k)
print(names)

Related

Changing value of a value in a dictionary within a list within a dictionary

I have a json like:
pd = {
"RP": [
{
"Name": "PD",
"Value": "qwe"
},
{
"Name": "qwe",
"Value": "change"
}
],
"RFN": [
"All"
],
"RIT": [
{
"ID": "All",
"IDT": "All"
}
]
}
I am trying to change the value change to changed. This is a dictionary within a list which is within another dictionary. Is there a better/ more efficient/pythonic way to do this than what I did below:
for key, value in pd.items():
ls = pd[key]
for d in ls:
if type(d) == dict:
for k,v in d.items():
if v == 'change':
pd[key][ls.index(d)][k] = "changed"
This seems pretty inefficient due to the amount of times I am parsing through the data.
String replacement could work if you don't want to write depth/breadth-first search.
>>> import json
>>> json.loads(json.dumps(pd).replace('"Value": "change"', '"Value": "changed"'))
{'RP': [{'Name': 'PD', 'Value': 'qwe'}, {'Name': 'qwe', 'Value': 'changed'}],
'RFN': ['All'],
'RIT': [{'ID': 'All', 'IDT': 'All'}]}

How to replace json value with list of items based on the key

How do I replace the json_object's blookup with blookup_values based on the ID's in the json blookup. I tried the below code by removing the ID's which are not present in the json_object['blookup']. The below code doesn't work. Could anyone please help.
blookup_values = [
{
"id":"123",
"name":"abc",
"date":"somedate",
"time":"sometime"
},
{
"id":"456",
"name":"def",
"date":"somedate",
"time":"sometime"
},
{
"id":"789",
"name":"ghi",
"date":"somedate",
"time":"sometime"
},
{
"id":"9999",
"name":"mmmmmm",
"date":"somedate",
"time":"sometime"
},
{
"id":"8888",
"name":"nnnnnn",
"date":"somedate",
"time":"sometime"
}
]
json_object = {
"id":"id_value",
"blookup": [{
"id":"123",
"type":"dddd"
},
{
"id":"456",
"type":"eeeee"
}
]
}
Code
result = [obj for obj in blookup_values if obj['id'] != json_object['blookup']]
Expected result
result = {
"id":"id_value",
"blookup": [{
"id":"123",
"name":"abc",
"date":"somedate",
"time":"sometime"
},
{
"id":"456",
"name":"def",
"date":"somedate",
"time":"sometime"
}
]
}
You have to get the id key from the json_object dictionaries:
result = [obj for obj in blookup_values if obj['id'] in [i["id"] for i in json_object['blookup']]]
First convert blookup_values into a dictionary keyed by id. Then you can replace json_object['blookup'] with a list comprehension made from this.
blookup_dict = {value['id']: value for value in blookup_values}
json_object['blookup'] = [blookup_dict[item['id']] for item in json_object['blookup']]
I’m not sure I completely understand what you are trying to do but what I gather is that you want to get the objects in blookup that do not have any of the same ids as the objects in json_objects. Is that correct?
Try to first get the id values of each object in json_object['blookup']. For example:
json_object_ids = [obj['id'] for obj in json_object['blookup']]
Next, filter the objects in blookup by slightly altering your list comprehension:
result = [obj for obj in blookup_values if obj['id'] not in json_object_ids]
The output would look something like this:
[{'id': '789', 'name': 'ghi', 'date': 'somedate', 'time':
'sometime'}, {'id': '9999', 'name': 'mmmmmm', 'date': 'som
edate', 'time': 'sometime'}, {'id': '8888', 'name': 'nnnnn
n', 'date': 'somedate', 'time': 'sometime'}]

How do I get the value of a dict item within a list, within a dict?

How do I get the value of a dict item within a list, within a dict in Python? Please see the following code for an example of what I mean.
I use the following lines of code in Python to get data from an API.
res = requests.get('https://api.data.amsterdam.nl/bag/v1.1/nummeraanduiding/', params)
data = res.json()
data then returns the following Python dictionary:
{
'_links': {
'next': {
'href': null
},
'previous': {
"href": null
},
'self': {
'href': 'https://api.data.amsterdam.nl/bag/v1.1/nummeraanduiding/'
}
},
'count': 1,
'results': [
{
'_display': 'Maple Street 99',
'_links': {
'self': {
'href': 'https://api.data.amsterdam.nl/bag/v1.1/nummeraanduiding/XXXXXXXXXXXXXXXX/'
}
},
'dataset': 'bag',
'landelijk_id': 'XXXXXXXXXXXXXXXX',
'type_adres': 'Hoofdadres',
'vbo_status': 'Verblijfsobject in gebruik'
}
]
}
Using Python, how do I get the value for 'landelijk_id', represented by the twelve Xs?
This should work:
>>> data['results'][0]['landelijk_id']
"XXXXXXXXXXXXXXXX"
You can just chain those [] for each child you need to access.
I'd recommend using the jmespath package to make handling nested Dictionaries easier. https://pypi.org/project/jmespath/
import jmespath
import requests
res = requests.get('https://api.data.amsterdam.nl/bag/v1.1/nummeraanduiding/', params)
data = res.json()
print(jmespath.search('results[].landelijk_id', data)

Remove keys from a nested dict (Python keys)

I'm pretty new in Python, thanks in advance for your help.
I built the following code (I tried the below, I used a dictionary within a dictionary).
The idea is to keep the keys (hair.color) with values(blonde). In this example: remove Micheal.
Code:
def answers(hair_questions):
try:
for i in people:
if people[i]["hair.color"]==hair_questions:
print(people[i])
else:
del people[i]
return people[i]
except:
print("Doesn´t exist")
answers("brown")
On People:
people={
"Anne":
{
"gender":"female",
"skin.color":"white",
"hair.color":"blonde",
"hair.shape":"curly"
}
,
"Michael":
{
"citizenship":"africa",
"gender":"male",
"hair.color":"brown",
"hair.shape":"curly"
}
,
"Ashley":
{
"gender":"female",
"citizenship":"american",
"hair.color":"blonde",
"hair.shape":"curly "
}
}
The code only check the first key: under the condition: values(blonde) i.e. (people[i]["hair.color"]!=brown) it works just for 1 key and then the code gets "stuck"
My current output:
"people"=
"Michael":
{
"citizenship":"africa",
"gender":"male",
"hair.color":"brown",
"hair.shape":"curly"
}
,
"Ashley":
{
"gender":"female",
"citizenship":"american",
"hair.color":"blonde",
"hair.shape":"curly "
}
Instead, I wanted:
"people"=
"Michael":
{
"citizenship":"africa",
"gender":"male",
"hair.color":"brown",
"hair.shape":"curly"
}
I want an output, for this case, (only) Michael.
You can't delete key while iterating for loop:
people={
"Anne":
{
"gender":"female",
"skin.color":"white",
"hair.color":"blonde",
"hair.shape":"curly"
},
"Michael":
{
"citizenship":"africa",
"gender":"male",
"hair.color":"brown",
"hair.shape":"curly"
},
"Ashley":
{
"gender":"female",
"citizenship":"american",
"hair.color":"blonde",
"hair.shape":"curly "
}
}
def answers(hair_questions):
my_dict = {}
for i in people:
if people[i]["hair.color"] in hair_questions:
my_dict[i] = people[i]
return my_dict
print(answers("brown"))
OR
def answers(hair_questions):
my_list = []
for i in people:
if people[i]["hair.color"] not in hair_questions:
my_list.append(i)
for i in my_list:
del people[i]
answers("brown")
print(people)
O/P:
{'Michael': {'citizenship': 'africa', 'gender': 'male', 'hair.color': 'brown', 'hair.shape': 'curly'}}
you can use list comprehension:
brown = {key:value for key,value in people.items() if people[key]["hair.color"] != "blonde"}
print (brown)
what is equal to:
brown= {}
for key,value in people.items():
if people[key]["hair.color"] != "blonde":
brown[key] = value
print (brown)
output:
{'Michael': {'citizenship': 'africa', 'gender': 'male', 'hair.color': 'brown', 'hair.shape': 'curly'}}

Regroup JSON file in a new format

I'm need a little help reordering this JSON data:
I've this file at this moment:
[{"aName":{"name":"somename","vendor":"vendor1"}},
{"bName":{"name":"somename","vendor":"vendor2"}},
{"cName":{"name":"othername","vendor":"vendor1"}
}]
I need re order it like this:
[{"name":"vendor1"},
{"child":[{"name":"somename","id":"aName"},
{"name":"othername","id":"cName"}]},
{"name":"vendor2"},
{"child":[{"name":"somename","id":"bName"}]}]
I was trying with this:
new format = []
for i in old_format:
new_format.setdefault(i['vendor'], []).append({"children":{"name":i['name'],"id":i}})
it's "closer", but not what I want
{
"vendor1":[
{
"children":{
"name":"somename",
"id":"aName"
}
},
{
"children":{
"name":"othername",
"id":"cName"
}
}
],
"vendor2":[
{
"children":{
"name":"somename",
"id":"bName"
}
}
]
}
I'll appreciate any advice.
The data representation you're using is a little strange... You have a lot of dictionaries with one entry, which suggests to me that you'd be better off rethinking how you store your data.
That said, this bit of code should do what you want:
vendors = {}
for entry in data:
for identifier, info in entry.items():
children = vendors.setdefault(info['vendor'], [])
children.append({
'name': info['name'],
'id': identifier
})
res = []
for vendor, children in vendors.items():
res.append({'name': vendor})
res.append({'child': children})
Here data is your input -- a list of dictionaries -- and res is the result:
[{'name': 'vendor2'},
{'child': [{'id': 'bName', 'name': 'somename'}]},
{'name': 'vendor1'},
{'child': [{'id': 'aName', 'name': 'somename'},
{'id': 'cName', 'name': 'othername'}]}]

Categories

Resources