Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to correctly parse JSON in Python

I use Databricks to get delta table info and I return the result as a JSON. The return goes by return json.dumps(value). However, when I receive the JSON it looks like 'key': 'value', with single quotes. Also, the booleans are displayed as True, False while null is displayed as None (which is normally since this is the way Python returns things). After receiving it into Python (precisely, Flask app), I forward this JSON to my .NET app but before that, I clean it with the following way:

json_value = json_value.replace("'", '"')
json_value = json_value.replace('True', 'true')
json_value = json_value.replace('False', 'false')
json_value = json_value.replace('None', 'null')

This thing worked for 2 months until one of my records got Cote d'Ivore as a value. This ‘cleaning’ replaced the single quote here with a double quote and that made my JSON crash on the .NET side. I parse the JSON on the .NET side by JsonConvert.DeserializeObject(response.Content).

Now, is there some automatic way to parse the JSON correctly at the Python side, without having to clean it by replacing and have a proper functionality when I’d send it to .NET?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to pass a dictionary object in json.dumps() instead of a string.

import json
a={'s':'asdas','fff':23,'ss':True, 'sssss':None}
res=json.dumps(a)
print (res)
##OUTPUT
## {"s": "asdas", "fff": 23, "ss": true, "sssss": null}

Assuming that you have string instead of a python dictionary; in that case you can convert that to dictionary using ast library

import ast
import json
value="{'s': 'asdas', 'fff': 23, 'ss': True, 'sssss': None}"
 #assuming it is in string format
value=ast.literal_eval(value) #convert string format dictionary to dictionary 
result=json.dumps(value)


Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading