简体   繁体   English

JSON 打印 Python 中的特定值

[英]JSON print specific value in Python

I am trying to print only project name from data which looks like this我正在尝试从看起来像这样的数据中仅打印项目名称

[{'Project Name': 'ABC'}, {'Customer Name': None}, {'Customer Address': None}, {'Project Description': 'Industries Pvt limited'}]

with my Python Code用我的 Python 代码

with open('project.json', 'r') as f:
    data = json.load(f)
    print(data)

for p in data:
    if 'Project Name' in p:
        print(p)
#Here it prints {'Project Name': 'ABC'}
# Print each property of the object
for p in data:
  print(p['Project Name'])

It prints out the Project Name as ABC but gives a Key Error like this它将项目名称打印为 ABC,但给出了这样的关键错误

KeyError: 'Project Name'

Use an if statement to see if p has a Project Name before trying to print it.在尝试打印之前,使用if语句查看p是否有Project Name

Your JSON file:您的 JSON 文件:

[
    {
        "Project Name": "ABC",
        "Customer Name": "None",
        "Customer Address": "None",
        "Project Description": "Industries Pvt limited"
    },
    {
        "Project Name": "QWERTY",
        "Customer Name": "None",
        "Customer Address": "None",
        "Project Description": "Some Text"
    }
]

And here's the python file:这是 python 文件:

import json

with open('my_json_file.json') as json_file:
    my_json = json.load(json_file)
    for data in my_json:
        print(data["Project Name"])

Output would look like this: Output 看起来像这样:

ABC
QWERTY

Your JSON is invalid.您的 JSON 无效。 You can check your JSON here: json lint您可以在此处查看您的 JSON: json lint

Use double quote marks for your JSON to make it valid.为您的 JSON 使用双引号以使其有效。

[
{
    "Project Name": "ABC"
},
{
    "Customer Name": "None"
},
{
    "Customer Address": "None"
},
{
    "Project Description": "Industries Pvt limited"
}

] ]

I suggest use a JSON editor to compose your JSON: json editor我建议使用 JSON 编辑器来编写您的 JSON: json 编辑器

You should not use for to iterate the items because the key 'Project Name' doesn't exist at the later indies.您不应该使用for来迭代这些项目,因为在后来的印度不存在关键的“项目名称”。 Or you have to use if statement to judge if the key name exists.或者你必须使用if语句来判断键名是否存在。

Another suggestion is that the data you provided seems like a list of dict rather than common json.另一个建议是,您提供的数据似乎是 dict 列表,而不是常见的 json。 Why not use ast?为什么不使用 ast? Try the codes below:试试下面的代码:

import ast

txt = "[{'Project Name': 'ABC'}, {'Customer Name': None}, {'Customer Address': None}, {'Project Description': 'Industries Pvt limited'}]"
data = ast.literal_eval(txt)

print(data[0]['Project Name'])

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

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