0

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!

3
  • 1
    Why not refer to the received structure as regular dictionary? Commented Jul 25, 2016 at 13:21
  • can you elaborate on your question? do you mean to try j_proper['Value'] ? i get the same error like with j Commented Jul 25, 2016 at 16:33
  • also, i would like to know why my question was down voted.. i researched the subject to the best of my abilities and did not succeed to reach my goal .. Commented Jul 25, 2016 at 16:43

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

I tried to edit and clean up the input and i have now this : {"OK": true, "Value": 43814485} "{\"OK\": true, \"Value\": 43814485}" {"OK": true, "Value": 43814485} Traceback (most recent call last): File "dirac.status_list.py", line 29, in <module> print j_proper['Value'] TypeError: string indices must be integers, not str
ok, i eliminated the json.dumps and the clean up line went well with json.loads directly. Thank you!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.