tiberhockey
tiberhockey

Reputation: 576

How to print clean string from JSON list // Dict?

so I have some problem to find how to print a clean string from JSON list // Dict files. I tried .join, .split method but it doesnt seem to work. Thank for the help guys

My code:

import json

with open("user.json") as f:
    data = json.load(f)

for person in data["person"]:
    print(person)

The JSON file

{
  "person": [
    {
      "name": "Peter",
      "Country": "Montreal",
      "Gender": "Male"
    },
    {
      "name": "Alex",
      "Country": "Laval",
      "Gender": "Male"
    }
  ]
}

The print output (Which is not the correct format I want)

{'name': 'Peter', 'Country': 'Montreal', 'Gender': 'Male'}
{'name': 'Alex', 'Country': 'Laval', 'Gender': 'Male'}

I want to have the output print format to be like this:

Name: Peter
Country: Montreal
Gender:Male

Upvotes: 0

Views: 101

Answers (3)

Amiram
Amiram

Reputation: 1295

If you want to print all the attributes in the person dictionary (with no exceptions) you can use:

for person in data["person"]:
    for k, v in person.items():
        print(k, ':', v)

Upvotes: 2

marcos
marcos

Reputation: 4510

for person in data["person"]:
    print(f"Name: {person['name']}")
    print(f"Country: {person['Country']}")
    print(f"Gender: {person['Gender']}")

for python3.6+

Upvotes: 1

Marsilinou Zaky
Marsilinou Zaky

Reputation: 1047

You can access values using their keys as follow

import json

with open("user.json") as f:
    data = json.load(f)

for person in data["person"]:
    print(f'Name: {person["name"]}')
    print(f'Country: {person["Country"]}')
    print(f'Gender: {person["Gender"]}')

Result:

Name: Peter
Country: Montreal
Gender: Male
Name: Alex
Country: Laval
Gender: Male

Upvotes: 1

Related Questions