Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JSON string to dict using Python

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"?

like image 306
Frias Avatar asked Dec 24 '10 19:12

Frias


People also ask

How do I convert a JSON to a dictionary in Python?

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.

Is JSON a dictionary in Python?

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() .

How do I convert a string to a JSON string in Python?

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.


2 Answers

json.loads()

import json  d = json.loads(j) print d['glossary']['title'] 
like image 121
Ignacio Vazquez-Abrams Avatar answered Oct 06 '22 02:10

Ignacio Vazquez-Abrams


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']) 
like image 23
Hussain Avatar answered Oct 06 '22 03:10

Hussain