Rahul Kumar
Rahul Kumar

Reputation: 2345

python unable to parse JSON Data

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?

Upvotes: 0

Views: 3899

Answers (2)

dvdnglnd
dvdnglnd

Reputation: 81

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).

Upvotes: 1

Jmons
Jmons

Reputation: 1786

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

Upvotes: 1

Related Questions