User avatar
addeswe
Posts: 27
Joined: Fri Jul 19, 2013 3:49 pm
Location: Sweden

[Python3] Parsing Json with json

Sun Feb 25, 2018 8:37 pm

So I've done some projects with json but then I came across this bastard creation and I honestly have no clue how to parse it.

Code: Select all

{"client1":{"percent":56},"client2":{"percent":53},"client3":{"percent":23},"client4":{"percent":60},"client5":{"percent":9}}
If I use json.loads, the client-key returns as a string, and the "value-json" is nowhere to be found. Checked with JSONlint, but they say it's a valid json.

Thanks in advance.
“Knock, knock.” - “Who’s there?” - very long pause…. - “Java.”
If a python knocks on your door and says “Hi, I’m a vacuum cleaner!” it’s not true. That’s a python.

User avatar
DougieLawson
Posts: 35791
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: [Python3] Parsing Json with json

Sun Feb 25, 2018 8:55 pm

Code: Select all

#!/usr/bin/python

json_s = '{"client1":{"percent":56},"client2":{"percent":53},"client3":{"percent":23},"client4":{"percent":60},"client5":{"percent":9}}'

import json
json_p = json.loads(json_s)

for key1, val in json_p.iteritems():
    print key1
    for key2 in val:
        print key2, val[key2]
Note: Having anything humorous in your signature is completely banned on this forum. Wear a tin-foil hat and you'll get a ban.

Any DMs sent on Twitter will be answered next month.

This is a doctor free zone.

User avatar
addeswe
Posts: 27
Joined: Fri Jul 19, 2013 3:49 pm
Location: Sweden

Re: [Python3] Parsing Json with json

Sun Feb 25, 2018 9:07 pm

I don't wanna be that guy, but I always hope that you are the one to answer since you always know the answers. :-)

Does not work in Python3, however. You pointed me in the right direction. So I managed to find the solution myself. Putting my answer here in case anyone else needs help with this subject:

Code: Select all

#!/usr/bin/python3
data = json.loads('{"client1":{"percent":56},"client2":{"percent":53},"client3":{"percent":23},"client4":{"percent":60},"client5":{"percent":9}}')
for x,y in jdata.items():                                                                                                                                                                                                                                                   
         print(x)
         print(y['percent'])
DougieLawson wrote:
Sun Feb 25, 2018 8:55 pm

Code: Select all

#!/usr/bin/python

json_s = '{"client1":{"percent":56},"client2":{"percent":53},"client3":{"percent":23},"client4":{"percent":60},"client5":{"percent":9}}'

import json
json_p = json.loads(json_s)

for key1, val in json_p.iteritems():
    print key1
    for key2 in val:
        print key2, val[key2]
“Knock, knock.” - “Who’s there?” - very long pause…. - “Java.”
If a python knocks on your door and says “Hi, I’m a vacuum cleaner!” it’s not true. That’s a python.

Return to “Python”