0

I am unable to parse the JSON data using python.

A webpage url is returning JSON Data

import requests
import json  

BASE_URL = "https://www.codechef.com/api/ratings/all"
data = {'page': page, 'sortBy':'global_rank', 'order':'asc', 'itemsPerPage':'40' }
r = requests.get(BASE_URL, data = data)
receivedData = (r.text)
print ((receivedData))

when I printed this, I got large text and when I validated using https://jsonlint.com/ it showed VALID JSON

Later I used

import requests
import json    

BASE_URL = "https://www.codechef.com/api/ratings/all"
data = {'page': page, 'sortBy':'global_rank', 'order':'asc', 'itemsPerPage':'40' }
r = requests.get(BASE_URL, data = data)
receivedData = (r.text)
print (json.loads(receivedData))

When I validated the large printed text using https://jsonlint.com/ it showed INVALID JSON

Even if I don't print and directly use the data. It is working properly. So I am sure even internally it is not loading correctly.

is python unable to parse the text to JSON properly?

3
  • 2
    You decoded the JSON and printed a text representation of a Python dictionary, which is not necessarily the same as the original JSON encoding. Commented May 5, 2017 at 13:07
  • 2
    The fact that you are getting any output from your second script is proof that Python is parsing the JSON just fine; you just aren't outputting JSON to the validator. Commented May 5, 2017 at 13:08
  • Even if I don't print and directly use the data. It is working properly. So I am sure even internally it is not loading correctly. Commented May 5, 2017 at 13:13

2 Answers 2

1

in short, json.loads converts from a Json (thing, objcet, array, whatever) into a Python object - in this case, a Json Dictionary. When you print that, it will print as a itterative and therefore print with single quotes..

Effectively your code can be expanded:

some_dictionary = json.loads(a_string_which_is_a_json_object)
print(some_dictionary)

to make sure that you're printing json-safe, you would need to re-encode with json.dumps

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

Comments

1

When you use python's json.loads(text) it returns a python dictionary. When you print that dictionary out it is not in json format.

If you want a json output you should use json.dumps(json_object).

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.