Ahmed jola
Ahmed jola

Reputation: 5

Find Value in JSON using python

I have json file contains : . How can I return the only results for agent_id 394903921554

enter code here

{ "agent_timeline": [{ "agent_id": 394903921554, "engagement_count": 0, "start_time": "2020-06-15T06:00:00.000000Z", "status": "invisible", "duration": 901.929878 }, { "agent_id": 397330457313, "engagement_count": 0, "start_time": "2020-06-15T06:00:00.000000Z", "status": "invisible", "duration": 901.929878 }, { "agent_id": 401565578994, "engagement_count": 0, "start_time": "2020-06-15T06:00:00.000000Z", "status": "invisible", "duration": 4.664595 }, { "agent_id": 394903921554, "engagement_count": 0, "start_time": "2020-06-15T06:00:11.000000Z", "status": "online", "duration": 901.929878 } ] }

Upvotes: 0

Views: 143

Answers (4)

bavaza
bavaza

Reputation: 11037

Try this:

import json

# load json from file, and covert to a Python object, in this case, a list of dictionaries
with open('my_file.json') as fp:
  lst = json.load(fp)

# use built-in filter() method to filter the list
matches = filter(lambda o: o["agent_id"] == 394903921554, lst)

# grab your dictionary
obj = next(matches)

Note that your text is not a valid json - assuming it is a list, it should be surrounded by '[]'

Upvotes: 0

Perfect
Perfect

Reputation: 1636

Suppose that you assign the full json result to a variable named results then you can filter it simply as following.

filtered = filter(lambda x: x['agent_id'] == 394903921554, results)
for item in filtered:
    print(item)

This will give you a generator.

Upvotes: 1

Sam
Sam

Reputation: 543

Assuming that structure is an array in the format of:

x = [
 {
    "agent_id": 394903921554,
    "engagement_count": 0,
    "start_time": "2020-06-15T06:00:00.000000Z",
    "status": "invisible",
    "duration": 901.929878
},
{
    "agent_id": 397330457313,
    "engagement_count": 0,
    "start_time": "2020-06-15T06:00:00.000000Z",
    "status": "invisible",
    "duration": 901.929878
},
{
    "agent_id": 401565578994,
    "engagement_count": 0,
    "start_time": "2020-06-15T06:00:00.000000Z",
    "status": "invisible",
    "duration": 4.664595
},
{
    "agent_id": 394903921554,
    "engagement_count": 0,
    "start_time": "2020-06-15T06:00:11.000000Z",
    "status": "online",
    "duration": 901.929878
    }
 ]

You could do the following:

[item for item in x if item['agent_id'] == 394903921554]

Upvotes: 0

Yilun Zhang
Yilun Zhang

Reputation: 9008

I assume in the file, the out-most bracket is square bracket ([]), otherwise it's not a valid json file.

You can read with:

import json
with open(FILENAME, "r") as f: 
    r = json.load(f)

Then, you will get a list of json objects. From there you can just do a simple filter to get the info you want:

result = [x for x in r if x["agent_id"] == 394903921554]
result = result[0] if result else None

The last line will take care of the case when agent_id is not in the file.

Upvotes: 1

Related Questions