1

Below code is running fine.

 import json
 json_data = '{"Detail":" Rs. 2000 Topup Rs.1779.99 Talktime","Amount":"2000","Validity":"Unlimited"}'
        json_parsed = json.loads(json_data)
        print(json_parsed['Detail'])
        print(json_parsed['Amount'])
        print(json_parsed['Validity'])

How to parse below json string? and How to display all values also?

json_data = '[{"Detail":" Rs. 2000 Topup Rs.1779.99 Talktime","Amount":"2000","Validity":"Unlimited"},{"Detail":" Rs. 1900 Topup Rs.1690.99 Talktime","Amount":"1900","Validity":"Unlimited"}]'

Please help me.

4
  • 2
    so what is the problem you are facing? Did you try your code against the json string? Commented Dec 31, 2016 at 16:35
  • The only difference is that the second string is an array of objects - so what exactly is your problem? Commented Dec 31, 2016 at 16:37
  • I don't how to parse this string [{"Detail":" Rs. 2000 Topup Rs.1779.99 Talktime","Amount":"2000","Validity":"Unlimited"},{"Detail":" Rs. 1900 Topup Rs.1690.99 Talktime","Amount":"1900","Validity":"Unlimited"}] Commented Dec 31, 2016 at 16:37
  • 1
    why giving down votes to my question? Don't know how to do that because of that only raised question. Actually i am very new to python. After i done lot of R&D only i got the first answer. Commented Dec 31, 2016 at 16:48

1 Answer 1

7

This json string is an array of objects, as opposed to a single object.

You'd parse it the same way with the json module, however instead of getting a single dictionary you would get a list of dictionaries.

you'd be able to display as so:

import json

json_data = '[{"Detail":" Rs. 2000 Topup Rs.1779.99 Talktime","Amount":"2000","Validity":"Unlimited"},{"Detail":" Rs. 1900 Topup Rs.1690.99 Talktime","Amount":"1900","Validity":"Unlimited"}]'

# convert to python data structure
d_list = json.loads(json_data)

# loop through the list
for d in d_list:
    # use get for safety
    print d.get('Detail')
    print d.get('Amount')

Regardless of the parsing language, python, javascript, php and so on, any json string or subset of a json string that has objects wrapped in [brackets] will be an array, and will need to be handled in a similar (language specific) fashion.

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

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.