Ankit Goyal
Ankit Goyal

Reputation: 33

Parsing a string into JSON

I am trying to parse a string with is in form of dictionary or lists of dictionaries.

And I am trying to parse it into a JSON object. But json.loads() is giving me an error.
How do I do this?

Thanks in Advance.

A sample portion of the file is as below:

{
"Andhra Pradesh": 
[
    {
        "code": "ANAN",
        "name": "Anantapur"
    }, 
    {
        "code": "CHDM",
        "name": "Chinnamandem"
    }, 
    {
        "code": "GUDR",
        "name": "Gudur"
    }, 
    {
        "code": "GUNT",
        "name": "Guntur"
    }, 
    {
        "code": "JANG",
        "name": "Jangareddy Gudem"
    }
],
"Karnataka": 
[
    {
        "code": "BANG",
        "name": "Bangalore"
    }, 
    {
        "code": "HUBL",
        "name": "Hubli"
    }, 
    {
        "code": "MLR",
        "name": "Mangalore"
    }, 
    {
        "code": "MYS",
        "name": "Mysore"
    }
],
"Madhya Pradesh":
[
    {
        "code": "BHOP",
        "name": "Bhopal"
    }, 
    {
        "code": "GWAL",
        "name": "Gwalior"
    }, 
    {
        "code": "IND",
        "name": "Indore"
    }, 
    {
        "code": "JABL",
        "name": "Jabalpur"
    }, 
    {
        "code": "UJJN",
        "name": "Ujjain"
    }
]
}

Upvotes: 2

Views: 149

Answers (3)

Aaron
Aaron

Reputation: 2393

In [1]: import json

In [2]: with open(r'YourTestFile.txt','r') as fh:
   ....:     a = json.load(fh)
   ....:     print a["Karnataka"][1]['code']
   ....:
HUBL

Upvotes: 2

Sidmeister
Sidmeister

Reputation: 856

import and use jsonify on the raw content, pack it and ship it.

repacked_json = json.dumps(raw_json_data) 
json_obj = json.loads(repacked_json)
return jsonify(result = json_obj)

Upvotes: 1

Sarath Kumar
Sarath Kumar

Reputation: 2353

json.loads()

try this one..

    import json 
    d = json.loads(sringToConvertToArray)
    print d['Andhra Pradesh']['code']

Upvotes: 3

Related Questions