简体   繁体   English

需要在python中获取JSON特定键的所有值

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

I am getting the following json data from pycurl in python.我从 python 中的pycurl获取以下json数据。 All I need to get those values into a list in python.我只需要将这些值放入 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.我需要将name key 的所有值都放入 python 列表中。

This is not a valid json data.这不是有效的 json 数据。 Single quotes aren't allowed in JSON files. JSON 文件中不允许使用单引号。 If that is the case, you need to first fix the JSON string.如果是这种情况,您需要先修复 JSON 字符串。

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)

jobtittles = list(map(lambda datum: datum['jobtitle'], jsonVal)) jobtittles = list(map(lambda 数据:数据 ['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.我使用上面的代码来做一些类似的事情,jsonVal = JSON as string 和 ['jobtitle'] 是 JSON 字符串中的键,jobtitles 是一个数组。

It worked wrapping the map() function with a list() function.它使用 list() 函数包装 map() 函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM