简体   繁体   中英

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

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

KeyError: 'Project Name'

Use an if statement to see if p has a Project Name before trying to print it.

Your JSON file:

[
    {
        "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:

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:

ABC
QWERTY

Your JSON is invalid. You can check your JSON here: json lint

Use double quote marks for your JSON to make it valid.

[
{
    "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

You should not use for to iterate the items because the key 'Project Name' doesn't exist at the later indies. Or you have to use if statement to judge if the key name exists.

Another suggestion is that the data you provided seems like a list of dict rather than common json. Why not use 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'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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