0

Learning Days Code to the get the data in JSON Format

#...
cursor.execute("SELECT * FROM user")
response = {
    "version": "5.2",
    "user_type": "online",
    "user": list(cursor),
}
response = json.dumps(response, sort_keys=False, indent=4, separators=(',', ': '))
print(response)
# ...

This produces output as

{
"version": "5.2",
"user_type": "online",
"user":
[
    {
        "name": "John",
        "id": 50
    },
    {
        "name": "Mark",
        "id": 57
    }
]
}

print(response["user"]) - TypeError: string indices must be integers

How do i access the values in JSON

3
  • json.dumps returns a string. Commented Sep 13, 2017 at 7:34
  • yes it return a string gone through the docs Commented Sep 13, 2017 at 7:57
  • Well, you cannot do response["user"] on a string response. What you want to do is response["user"] on the old value of response before you turned it into a string using json.dumps. Commented Sep 13, 2017 at 8:01

1 Answer 1

1

json.dumps return a string, need a small conversion something like this, not sure is this the exact method to do

Solution:

response = JSONEncoder().encode(response )
response = JSONDecoder().decode(response )
response = json.loads(response )
print(response['user'[0]['id'])
Sign up to request clarification or add additional context in comments.

2 Comments

Why would you decode a JSON string right after encoding it?
well, newbie, but this works, don't know how. can someone explain why this works ?

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.