1

In this json array:

json_string=[{"Id": "report","Value": "3001"},{"Id": "user","Value": "user123"}]

How can I get back user123 if I pass in user

When I try to do this:

content = json.loads(json_string) 
content['user']

I get an error that says you have to use integer to reference an element.

I am brand new to Python.

Thanks!

0

2 Answers 2

3

content is a list so you should get the element by index first:

>>> content[1]['Value']
'user123'

>>> for d in content:
...     if 'user' in d.values():
...         print d['Value']
'user123'

Assuming user is always mapped to Id:

>>> for d in content:
...     if d['Id'] == 'user':
...         print d['Value']

One liner:

 >>> [d['Value'] for d in content if d['Id'] == 'user'][0]
 'user123'
Sign up to request clarification or add additional context in comments.

6 Comments

Or more generally, [ x for x in content where x['Id'] == "user"][0]["Value"]
Thank you! There's no way of saying, give me the value where the element Id is User? Without having to reference the index? I know I can loop over it, but just thought it could be done in one line.
@chepner, Yes!! that's it. Thank you!
I think it is, anyway. I've edited my comment several times so far :)
@chepner I assumed 'user' may not have to be mapped to Id always.
|
0

Assuming you want to focus on the first occurrence of an element in the list with a given field (e.g. 'Id') with a certain value (e.g. 'user'):

def look_for(string, field, val):
    return next((el['Value'] for el in string if el[field] == val))

json_string = [{"Id": "report","Value": "3001"}, {"Id": "user","Value": "user123"}]
found_val = look_for(json_string, 'Id', 'user')

produces

'user123'

Obviously, also the output field can become a parameter instead of being hardcoded to Value

Comments

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.