2

How do I format my JSON output so that it looks human readable and I have a JSON file that looks like this:

{
"user1":{
    "Country":[
        "China", "USA", "Nepal"
    ],
     "Name": [
        "Lisbon"
    ]
},

"user2":{
    "Country":[
        "Sweden", "China", "USA"
    ],
     "Name": [
        "Jade"
    ]
},

"user3":{
    "Country":[
        "India", "China", "USA"
    ],
     "Name": [
        "John"
    ]
}

Here's my code:

user = raw_input("Enter user's name: ")
with open('Users.json') as f:
    data = json.load(f)

for k, v in data.items():
    if any(x in data[user]['Country'] for x in v['Country']):
        print(v['Name'])

So far my output looks like this:

[u'Lisbon']
[u'Jade']
[u'John']

I would like an output that looks like this, how do I go around that?:

Lisbon
Jade
John
kraljevocs
  • 115
  • 1
  • 2
  • 12

3 Answers3

1

You just need to change print(v['Name']) for print(v['Name'][0])

luis.galdo
  • 543
  • 5
  • 20
0

The u in u'Jade' signifies that the string is encoded in Unicode. You can use print(unicode(v['Name'][0])) if you wish to print the bare string, but it makes no difference in the underlying data type.

You probably want to check out pretty-printing JSON if you will continue working on with JSON objects in Python.

hyperTrashPanda
  • 838
  • 5
  • 18
0

Thank you for the various answers people! But I managed to find figure it out on my own, I tweaked my print statement into this!

userName = raw_input("Enter user's name: ")
with open('extracted_data.json') as f:
    data = json.load(f)

for k, v in data.items():
    if any(x in data[userName]['Acceptable_country'] for x in v['Acceptable_country']):
        print(", ".join(v['Name']))
kraljevocs
  • 115
  • 1
  • 2
  • 12