1

I have below JSON String. Now I want to extract each individual field from that JSON string.

So I decided to create a method parse_json which will accept a variable that I want to extract from the JSON String.

Below is my python script -

#!/usr/bin/python

import json

jsonData = '{"pp": [0,3,5,7,9], "sp": [1,2,4,6,8]}'

def parse_json(data):
    jj = json.loads(jsonData)
    return jj['+data+']

print parse_json('pp')

Now whenever I an passing pp to parse_json method to extract its value from the JSON String, I always get the error as -

return jj['+data+']
KeyError: '+data+'

Any idea how to fix this issue? As I need to pass the variable which I am supposed to extract from the JSON String?

2 Answers 2

3

You probably just want this:

    return jj[data]

Your code is trying to look up a key named literally '+data+', when instead what you want to do is look up the key with a name of the function's parameter.

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

Comments

2

Just use data parameter itself.


Replace following line:

return jj['+data+'] # lookup with `+data+`, not `pp`

with:

return jj[data]

Comments

Your Answer

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