我想提取 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"
}
Run Code Online (Sandbox Code Playgroud)
输出:
listText = ["contact solution - COUPON","Falafel (bulk)","brita filters"]
Run Code Online (Sandbox Code Playgroud)
更新:
我从 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"
Run Code Online (Sandbox Code Playgroud)
使用 Pandas,我将列的项目转换为列表。
with open("data/output.csv", "rb") as csvfile:
df = pd.read_csv(csvfile)
addData = df.Address
listfiels= df.jsonfile
Run Code Online (Sandbox Code Playgroud)
现在,我想获取 Json 文件中的“文本”列表,以这种方式将其存储到其他 json 文件中。我需要 YYY 列表,每次都选择 XXX。
output = [ {
"type": "User",
"name": {
"status": "Single",
"adress":coordinates
"details": XXXX }
}
for da,coordinates in zip(textData, addData,YYYY )]
Run Code Online (Sandbox Code Playgroud)
这有意义吗?我用 JS 做了这个,没有任何问题。
var globalData = data.map(function(d) {
return JSON.parse(d.Jsonfile);
});
Run Code Online (Sandbox Code Playgroud)
我可以毫无问题地访问文本字段。
UPDATE2: j = json.loads(listfiels[0]) print(j['text'])
我可以成功打印:“联系解决方案 - COUPON”
使用列表理解:
>>> 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']
Run Code Online (Sandbox Code Playgroud)
map与以下一起使用operator.itemgetter:
>>> import operator
>>> list(map(operator.itemgetter('text'), lst)) # Omit `list` in Python 2.x
['contact solution - COUPON', 'Falafel (bulk)', 'brita filters']
Run Code Online (Sandbox Code Playgroud)