Python JSON Element Access with 2 responses - python

I can't find the right search term to come up with an answer to this but I know it's a noob question. I'm accessing an API which returns either:
{
"Items":[
{
"Id":"12",
"Type":"Address",
"Highlight":"564754165545",
}
]
}
or sometimes:
{
"Items":[
{
"Id":"12",
"Type":"BuildingNumber",
"Highlight":"145454479854",
},
{
"Id":"12",
"Type":"Address",
"Highlight":"564754165545",
}
]
}
I need to get the "highlight" element data but only when type is address from a reply.
Thanks for your help and sorry I couldn't work out the name of the multiple rows to find this for myself.

Items is a list of dicts. According to your example, sometimes the list contains one item, and other times it contains two items.
for item in foo['Items']:
if item['Type'] == 'Address':
print (item['Highlight'])

Use following code
new_items = [ j for j in JSON['Items'] if j.get('Type') == 'Address' ]
JSON = {'Items' : new_items }
for only heighlight data
new_items = [ j.get('heighlight') for j in JSON['Items'] if j.get('Type') == 'Address' ]

To obtain a list of highlights objects with Address Type
[highlight for highlight in respose['Items'] if highlight['Type'] == 'Address']

Related

python - Json data with different keys

I am trying to store two run options in Json. My attempt is as below. Is this a sensible way to organise Json object? Also how can I read either of them into tuples? I tried tuple([(item['opt_one'],item['val_one']) for item in config['opts']]) but git a key error. Many thanks for your help.
"opts":[
{
"opt_one": "one_option",
"val_one" : "value_one"
},
{
"opt_two": "two_option",
"val_two" : "value_two"
}
]
# or it can be done in 1 line
print(tuple(map(lambda v: tuple(v.values()), J['opts'])))
import json
j = """
{"opts":[
{
"opt_one": "one_option",
"val_one" : "value_one"
},
{
"opt_two": "two_option",
"val_two" : "value_two"
}
]
}
"""
# note the braces around "opts"
J = json.loads(j) #turns it into a python object
print(J) #see!
# the long way to do it, but you can see the process
R = []
for item in J['opts']:
r = []
for v in item.values():
r.append(v)
R.append(tuple(r))
print(tuple(R)) # solution

How do I extract a list item from nested json in Python?

I have a json object and I'm trying to extract a couple of values from a nested list. Then print them in markup. I'm getting and error - AttributeError: 'list' object has no attribute 'get'
I understand that it's a list and I can't preform a get. I've been searching for the proper method for a few hours now and I'm running out of steam. I'm able to get the Event, but not Value1 and Value2.
This is the json object
{
"resource": {
"data": {
"event": "qwertyuiop",
"eventVersion": "1.05",
"parameters": {
"name": "sometext",
"othername": [
""
],
"thing": {
"something": {
"blah": "whatever"
},
"abc": "123",
"def": {
"xzy": "value"
}
},
"something": [
"else"
]
},
"whatineed": [{
"value1": "text.i.need",
"value2": "text.i.need.also"
}]
}
}
}
And this is my function
def parse_json(json_data: dict) -> Info:
some_data = json_data.get('resource', {})
specific_data = some_data.get('data', {})
whatineed_data = specific_data.get('whatineed', {})
formatted_json = json.dumps(json_data, indent=2)
description = f'''
h3. Details
*Event:* {some_data.get('event')}
*Value1:* {whatineed_data('value1')}
*Value2:* {whatineed_data('value2')}
'''
From the data structure, whatineed is a list with a single item, which in turn is a dictionary. So, one way to access it would be:
whatineed_list = specific_data.get('whatineed', [])
whatineed_dict = whatineed_list[0]
At this point you can do:
value1 = whatineed_dict.get('value1')
value2 = whatineed_dict.get('value2')
You can change your function to the following:
def parse_json(json_data: dict) -> Info:
some_data = json_data.get('resource')
specific_data = some_data.get('data', {})
whatineed_data = specific_data.get('whatineed', {})
formatted_json = json.dumps(json_data, indent=2)
description = '''
h3. Details
*Event:* {}
*Value1:* {}
*Value2:* {}
'''.format(some_data.get('data').get('event'),whatineed_data[0]['value1'], whatineed_data[0]['value2'])
Since whatineed_data is a list, you need to index the element first
Python handles json as strings unless they are coming directly from a file. This could be the source for some of your problems. Also this article might help.
Assuming that "whatineed" attribute is really a list, and it's elements are dicts, you can't call whatineed.get asking for Value1 or Value2 as if they are attributes, because it is a list and it don't have attributes.
So, you have two options:
If whatineed list has a single element ever, you can access this element directly and than access the element attributes:
element = whatineed[0]
v1 = element.get('value1', {})
v2 = element.get('value2', {})
Or, if whatineed list can have more items, so, you will need to iterate over this list and access those elements:
for element in whatineed:
v1 = element.get('value1', {})
v2 = element.get('value2', {})
## Do something with values

How to search for specific value in Json array using Python

I'm using a website's API to get information. It outputs 100 values.
What is the best practice of searching for a specific value in this array?
The array looks something like this:
{
"success":true,
"data":
{
"array":
[
{
"id":"1","name":"Value1"
},
{
"id":"2","name":"Value2"
}
]
}
}
I try searching for the data using this snippet I found elsewhere, however it does not work:
for name in (r.json()['data']['array'][0]['name']):
if r.json()['data']['array'][0] == s_name:
ident = r.json()['data']['array'][0]['id']
name = r.json()['data']['array'][0]['name']
print (name + ' - ' + ident)
else:
print ('Nothing was found.')
So if I was trying to reference Value1 how would I do this using Python?
Please note: I'm a rookie developer, first time using Json, not very experienced with Python.
All help is greatly appreciated.
Here is a one-liner example for searching:
aaa = {
"success":True,
"data":
{
"array":
[
{
"id":"1","name":"Value1"
},
{
"id":"2","name":"Value2"
}
]
}
}
[a['name'] for a in aaa['data']['array'] if a['id']=='1']
This will return all the found cases, or an empty array if nothing is found
Not sure where that piece of code came from but it looks very wrong.
Just looking at the structure you can do something like:
for attrs in r.json()['data']['array']:
if attrs['name'] == s_name:
ident = attrs['id']
name = attrs['name']
print(name, '-', ident)
break
else:
print('Nothing found!')
Your code can be simplified a lot:
# no need to call `r.json` so many times, can simply save it to a variable
json_data = r.json()
for item in json_data["data"]["array"]:
if item["name"] == "Value1":
# do something...

Logic for building converter using python dictionary values

I have such slice of loaded json tp python dictionary (size_dict):
{
"sizeOptionName":"XS",
"sizeOptionId":"1528",
"sortOrderNumber":"7017"
},
{
"sizeOptionName":"S",
"sizeOptionId":"1529",
"sortOrderNumber":"7047"
},
{
"sizeOptionName":"M",
"sizeOptionId":"1530",
"sortOrderNumber":"7095"
}
and I have products with size Id (dictionary_prod):
{
"catalogItemId":"7627712",
"catalogItemTypeId":"3",
"regularPrice":"0.0",
"sizeDimension1Id":"1528",
"sizeDimension2Id":"0",
}
I need to make such as output for any product:
result_dict = {'variant':
[{"catalogItemId":"7627712", ...some other info...,
'sizeName': 'XS', 'sizeId': '1525'}}]}
so I need to convert size ID and add it to new result object
What is the best pythonic way to do this?
I dont know how to get right data from size_dict
if int(dictionary_prod['sizeDimension1Id']) > o:
(result_dict['variant']).append('sizeName': size_dict???)
As Tommy mentioned, this is best facilitated by mapping the size id's to their respective dictionaries.
size_dict = \
[
{
"sizeOptionName":"XS",
"sizeOptionId":"1528",
"sortOrderNumber":"7017"
},
{
"sizeOptionName":"S",
"sizeOptionId":"1529",
"sortOrderNumber":"7047"
},
{
"sizeOptionName":"M",
"sizeOptionId":"1530",
"sortOrderNumber":"7095"
}
]
size_id_map = {size["sizeOptionId"] : size for size in size_dict}
production_dict = \
[
{
"catalogItemId":"7627712",
"catalogItemTypeId":"3",
"regularPrice":"0.0",
"sizeDimension1Id":"1528",
"sizeDimension2Id":"0",
}
]
def make_variant(idict):
odict = idict.copy()
size_id = odict.pop("sizeDimension1Id")
odict.pop("sizeDimension2Id")
odict["sizeName"] = size_id_map[size_id]["sizeOptionName"]
odict["sizeId"] = size_id
return odict
result_dict = \
{
"variant" : [make_variant(product) for product in production_dict]
}
print(result_dict)
Your question is a little confusing but it looks like you have a list (size_dict) of dictionaries that contain some infroamtion and you want to do a lookup to find a particular element in the list that contains the SizeOptionName you are interested in so that you can read off the SizeOptionID.
So first you could organsie your size_dict as a dictionary rather than a list - i.e.
sizeDict = {"XS":{
"sizeOptionName":"XS",
"sizeOptionId":"1528",
"sortOrderNumber":"7017"
}, "S": {
"sizeOptionName":"S",
"sizeOptionId":"1529",
"sortOrderNumber":"7047"
}, ...
You could then read off the SizeOptionID you need by doing:
sizeDict[sizeNameYouAreLookingFor][SizeOptionID]
Alternative you could keep your current structure and just search the list of dictionaries that is size_dict.
So:
for elem in size_dict:
if elem.SizeOptionID == sizeYouAreLookingFor:
OptionID = elem.SizeOptionId
Or perhaps you are asking something else?

How to loop through JSON in Python

I can't figure out how to loop though a JSON object that is deeper than 1 level. The object is:
{
"data":[
{
"id":"251228454889939/insights/page_fan_adds_unique/day",
"name":"page_fan_adds_unique",
"period":"day",
"values":[
{
"value":9,
"end_time":"2012-05-29T07:00:00+0000"
},
{
"value":5,
"end_time":"2012-05-30T07:00:00+0000"
}
],
"title":"Daily New Likes",
"description":"Daily The number of new people who have liked your Page (Unique Users)"
},
{
"id":"251228454889939/insights/page_fan_adds/day",
"name":"page_fan_adds",
"period":"day",
"values":[
{
"value":9,
"end_time":"2012-05-29T07:00:00+0000"
},
{
"value":5,
"end_time":"2012-05-30T07:00:00+0000"
}
],
"title":"Daily New Likes",
"description":"Daily The number of new people who have liked your Page (Total Count)"
}
]
}
Code:
def parseJsonData(data):
output_json = json.loads(data)
for i in output_json:
print i
for k in output_json[i]:
print k
How come I can't access the object like: output_json[data][id]?
I get an error if I try this:
string indice must be an integer
Being that your "data" key is actually a list of objects, you cannot access the items by their "id" field directly. You would need to access each item by a list index such as:
output_json["data"][0]["id"]
Now, if what you want to do is to be able to index the members of "data" by the "id" field as the key, you could reformat your data:
# make "data" a dict {id: item, }, instead of list [item1, item2, ...]
output_json['data'] = dict((item['id'], item) for item in json_data['data'])
print output_json['data']
# {'251228454889939/insights/page_fan_adds_unique/day': ...
print output_json['data']['251228454889939/insights/page_fan_adds_unique/day']
# {'description': 'Daily The number of new p ...
# ways to loop over "data"
for id_, item in output_json['data'].iteritems():
print id_, item
for item in output_json['data'].itervalues():
print item
Otherwise what you have to do is just loop over "data", since there is no real correlation between the index and the object:
for item in output_json["data"]:
print item['id']
# 251228454889939/insights/page_fan_adds_unique/day
# 251228454889939/insights/page_fan_adds/day
What you pasted is not valid JSON. There is an unmatched [ after "data".
Based on this, I would guess that maybe the data isn't what you think it is. If the value of output_json[data] is a list, then you won't be able to access output_json[data][id]. Instead you'll have to do something like output_json[data][0][id], where the [0] accesses the first item in the list.

Categories