Python:在Json文件中获取一个属性(按值)的项

2024-09-20 05:45:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我想提取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" 
    }

输出:

^{pr2}$

更新:

我从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);
        });

我可以访问文本字段没有问题。在

更新2: j=json.loads(列表字段[0]) 打印(j[“文本”])

我可以成功打印:“联系解决方案-优惠券”


Tags: 文件text文本anidjsontruedf
2条回答
   jsonString=open("file.json").read()
   import json
   myList = [e['text'] for e in json.loads(jsonString)]

使用列表理解:

>>> 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']

mapoperator.itemgetter一起使用:

^{pr2}$

相关问题 更多 >