I'm a little bit confused with JSON in Python. To me, it seems like a dictionary, and for that reason I'm trying to do that:
{ "glossary": { "title": "example glossary", "GlossDiv": { "title": "S", "GlossList": { "GlossEntry": { "ID": "SGML", "SortAs": "SGML", "GlossTerm": "Standard Generalized Markup Language", "Acronym": "SGML", "Abbrev": "ISO 8879:1986", "GlossDef": { "para": "A meta-markup language, used to create markup languages such as DocBook.", "GlossSeeAlso": ["GML", "XML"] }, "GlossSee": "markup" } } } } }
But when I do print dict(json)
, it gives an error.
How can I transform this string into a structure and then call json["title"]
to obtain "example glossary"?
To convert json to dict in Python, use the json. load() function. The json. load() is a built-in function that deserializes json data to a Python object.
Python has a library called json that allows you to convert JSON into dictionary and vice versa, write JSON data into a file, read JSON data from a file, among other things that we shall learn. Important methods in json : dumps(), dump(), load() and loads() .
Use the json. you can turn it into JSON in Python using the json. loads() function. The json. loads() function accepts as input a valid string and converts it to a Python dictionary.
json.loads()
import json d = json.loads(j) print d['glossary']['title']
When I started using json, I was confused and unable to figure it out for some time, but finally I got what I wanted
Here is the simple solution
import json m = {'id': 2, 'name': 'hussain'} n = json.dumps(m) o = json.loads(n) print(o['id'], o['name'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With