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
2

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.