Reputation: 307
I get a nested Json as request response, trying to exact the name
field. However after converting it to Json, what supposed to be a dictionary turned to a string. Could you please help pointing out what I did wrong and how to handle this? Many thanks.
sample result from print response.json()
:
{'subject': 'order', 'id':20, 'info':{"result":"record","name":"orderrecords", "items":[{"name":"apple","type":"food"},{"name":"orange","type":"food"}]}
I tried with :
response= requests.get("url")
info= response.json()
print (type(info["items"]) #it is str here
What I am looking to achieve is having a dictionary with value of "name", the one with in items, as keys and the "type" as value. Like {"apple":"food", "orange": "food"}
Upvotes: 0
Views: 3331
Reputation: 43
When the json result is printed on console expected to have result in '. But the object/variable(info) might have the json format.
First of all the result obtained has syntax issue. please add curly braces:
info = {'subject': 'order', 'id':20, 'info':{"result":"record","name":"orderrecords", "items":[{"name":"apple","type":"food"},{"name":"orange","type":"food"}]}}
Even if the object is dictionary:
print(info["info"]["items"][0])
print(info["info"]["items"][1])
if the result is in json then please import json & load as above suggestion
Upvotes: 0
Reputation: 9552
The json
object returned is not a valid one as json
should have "
and not '
.
You can use replace()
to replace '
with "
and then convert to json
object:
import json
data = '''{'subject': 'order', 'id':20, 'info':{"result":"record","name":"orderrecords", "items":[{"name":"apple","type":"food"},{"name":"orange","type":"food"}]}}''' # there is also a missing } in the end
data = data.replace("'", '"')
data_json = json.loads(data)
res = {elt["name"] : elt["type"] for elt in data_json["info"]["items"]}
print(res)
Output:
{'apple': 'food', 'orange': 'food'}
Note: This will also replace any single quotes which are present as part of data if any.
Upvotes: 2