我想提取json文件的所有值。 例如,我有这个对象,我想获得所有“文本”值。 我怎样才能做到这一点 ?
list= [
{
"text": "contact solution - COUPON",
"listId": "1",
"id": "4",
"leaf": "true"
},
{
"text": "Falafel (bulk)",
"listId": "1",
"id": "161",
"leaf": "true"
},
{
"text": "brita filters",
"listId": "1",
"id": "166",
"leaf": "false"
}
输出:
listText = ["contact solution - COUPON","Falafel (bulk)","brita filters"]
更新:
我从CSV文件中获取这些数据。
text,listId,id,leaf, jsonfile
"1","is","an","example","{ "text": "contact solution - COUPON", "listId": "1", "id": "4","leaf": "true"}"
"2","is","an","example"," { "text": "Falafel (bulk)","listId": "1", "id": "161", "leaf": "true" }"
"3","is","an","example"," { "text": "Falafel (bulk)","listId": "1","id": "161","leaf": "true" }"
"4","is","an","example"," { "text": "brita filters","listId": "1","id": "166","leaf":"false" }"
"5","is","an","example"
"6","is","an","example"
"7","is","an","example"
使用Pandas,我将列的项目转换为列表。
with open("data/output.csv", "rb") as csvfile:
df = pd.read_csv(csvfile)
addData = df.Address
listfiels= df.jsonfile
现在,我想在Json文件中获取一个“text”列表,以这种方式存储其他json文件。 我需要YYY列表,每次都选择XXX。
output = [ {
"type": "User",
"name": {
"status": "Single",
"adress":coordinates
"details": XXXX }
}
for da,coordinates in zip(textData, addData,YYYY )]
这是否有意义? 我使用JS做了这个没有问题。
var globalData = data.map(function(d) {
return JSON.parse(d.Jsonfile);
});
我可以毫无问题地访问文本字段。
UPDATE2: j = json.loads(listfiels [0]) 打印(j [ '文本'])
我可以成功打印:“联系方式 - COUPON”
答案 0 :(得分:3)
使用列表理解:
>>> lst = [
... {
... "text": "contact solution - COUPON",
... "listId": "1",
... "id": "4",
... "leaf": "true"
... },
... {
... "text": "Falafel (bulk)",
... "listId": "1",
... "id": "161",
... "leaf": "true"
... },
... {
... "text": "brita filters",
... "listId": "1",
... "id": "166",
... "leaf": "false"
... }
... ]
>>> [d['text'] for d in lst]
['contact solution - COUPON', 'Falafel (bulk)', 'brita filters']
将map
与operator.itemgetter
一起使用:
>>> import operator
>>> list(map(operator.itemgetter('text'), lst)) # Omit `list` in Python 2.x
['contact solution - COUPON', 'Falafel (bulk)', 'brita filters']
答案 1 :(得分:1)
jsonString=open("file.json").read()
import json
myList = [e['text'] for e in json.loads(jsonString)]