Adrian Sevcenco
Adrian Sevcenco

Reputation: 311

python :: howto parse json and access element

I am trying to parse a json that in the raw form look like this :

{'OK': True, 'Value': 43768746}  

i am doing this :

line = line.strip().decode("utf-8")  
j_proper = json.dumps(line)  
j = json.loads(j_proper)  
print  j['Value']  

but i get the error :

print  j['Value']  
TypeError: string indices must be integers  

if i print line, j_proper, j and their types i get this :

{'OK': True, 'Value': 43768746}  
< type 'unicode'>  
"{'OK': True, 'Value': 43768746}"  
< type 'str'>  
{'OK': True, 'Value': 43768746}  
< type 'unicode'>  

What is the correct recipe to parse such a json and access the "Value" number?
Thank you!

Upvotes: 0

Views: 198

Answers (1)

Andrei Kovacs
Andrei Kovacs

Reputation: 171

The JSON string is incorrect. The proper format would be:

{"OK": true, "Value": 43768746}

Changes:

  • double quotes instead of single quotes
  • lower "t" instead of "T" for "true"

Example:

line = '{"OK": true, "Value": 43768746}'
j = json.loads(line)

{u'OK': True, u'Value': 43768746}

j['Value'] = 43768746
j['OK'] = True

Upvotes: 4

Related Questions