Home > database >  How to correctly parse JSON in Python
How to correctly parse JSON in Python

Time:03-02

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?

CodePudding user response:

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)


  • Related