0

I have a JSON text grabbed from an API of a website:

{"result":"true","product":{"made":{"Taiwan":"Taipei","HongKong":"KongStore","Area":"Asia"}}}

I want to capture "Taiwan" and "Taipei" but always fail.

Here is my code:

import json
weather = urllib2.urlopen('url')
wjson = weather.read()
wjdata = json.loads(wjson)
print wjdata['product']['made'][0]['Taiwan']

I always get the following error: Keyword 0 error

Whats the correct way to parse that json?

4
  • 4
    wjdata['product']['made']['Taiwan']? Commented Nov 27, 2019 at 13:13
  • @Rakesh I get the following error: TypeError: string indices must be integers Commented Nov 27, 2019 at 13:20
  • Errors are pointless without context, please post full error message and print exact json that you receive. Commented Nov 27, 2019 at 13:44
  • actually he is not receiving json he is receiving string of dictionary. @xiholac761 please check my post Commented Nov 27, 2019 at 13:49

2 Answers 2

1

You are indexing an array where there are none. The JSON is the following:

{ 
    "result":"true",
    "product": {
        "made": {
            "Taiwan":"Taipei",
            "HongKong":"KongStore",
            "Area":"Asia"
        }
    }
}

And the above contains no arrays.

You are assuming the JSON structure to be something like this:

{ 
    "result":"true",
    "product": {
        "made": [
            {"Taiwan":"Taipei"},
            {"HongKong":"KongStore"},
            {"Area":"Asia"}

        ]            
    }
}

From a brief look at the doc pages for the json package, I found this conversion table: Conversion table using json.loads

It tells us that a JSON object translates to a dict. And a dict has a method called keys, which returns a list of the keys.

I suggest you try something like this:

#... omitted code
objectKeys = wjdata['product']['made'].keys()

# You should now have a list of the keys stored in objectKeys.
for key in objectKeys:
    print key
    if key == 'Taiwan':
        print 'Eureka'

I haven't tested the above code, but I think you get the gist here :)

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

1 Comment

You're right, there are no arrays. Is it possible to parse "Taipei" from that json data and print it?
0

wjdata['product']['made']['Taiwan'] works

3 Comments

Sadly it results in an error: TypeError: string indices must be integers
Are you trying to load a dynamic data(with multiple keys) or are you trying to get just key Taiwan
Just the key Taiwan.

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.