Linux Automations
Linux Automations

Reputation: 55

Need to get all values of a particular key of JSON in python

I am getting the following json data from pycurl in python. All I need to get those values into a list in python.

OUTPUT:
[{ 'name' : 'aaa', 'contact' : '123' },{ 'name' : 'bbb', 'contact' : '345' },{ 'name' : 'ccc', 'contact' : '555' }]

I need to get all those values of name key into a python list.

Upvotes: 0

Views: 4140

Answers (2)

Dennis C.
Dennis C.

Reputation: 1

jobtittles = list(map(lambda datum: datum['jobtitle'], jsonVal))

I used the above code in order to do something simila, jsonVal = JSON as string and ['jobtitle'] is the key in the JSON string, jobtitles is an array.

It worked wrapping the map() function with a list() function.

Upvotes: 0

hspandher
hspandher

Reputation: 16733

This is not a valid json data. Single quotes aren't allowed in JSON files. If that is the case, you need to first fix the JSON string.

import json

json_data_string = "[{ 'name' : 'aaa', 'contact' : '123' },{ 'name' : 'bbb', 'contact' : '345' },{ 'name' : 'ccc', 'contact' : '555' }]"
json_data_string = json_data_string.replace("'", "\"") #provided JSON content doesn't contains single quotes as part of values.

data = json.loads(json_data_string)
names = map(lambda datum: datum['name'], data)

Upvotes: 9

Related Questions