Reputation: 2755
i have a dictionary in python with one string variable like below (Of Course there are many other string fields there in the json, but only few are json escaped strings)
obj_dict = dict(details="{\"name\":\"Vyshakh\",\"martial_status\" : \"Single\"}")
how can I convert such an object to normal json as below:
{
details : {
name : "Vyshakh",
martial_status : "Single"
}
}
In Java using Jackson I can annotate a field using @JsonRawValue, what is the best way in Python to achieve the same
Upvotes: 0
Views: 4571
Reputation: 23
In Python, I had success making a method like this:
def db_format_json(value: json):
return json.dumps(json.loads(value))
The loads removes the slashes while making it a Python dict, then the dumps puts it back into json without slashes.
Upvotes: 0
Reputation: 4471
Override the encoder to return the raw json string.
import json
class RawJSON(str): pass
origEnc = json.encoder.encode_basestring_ascii
def rawEnc(obj):
if isinstance(obj, RawJSON):
return obj
return origEnc(obj)
json.encoder.encode_basestring_ascii = rawEnc
obj_dict = dict(details=RawJSON("{\"name\":\"Vyshakh\",\"martial_status\" : \"Single\"}"))
print(json.dumps(obj_dict)) # {"details": {"name":"Vyshakh","martial_status" : "Single"}}
Upvotes: 2
Reputation: 9601
The json
module from the standard library has json.loads()
for this.
You pass the JSON-compatible string to json.loads()
and it will return a dictionary object.
From the Python interpreter:
>>> import json
>>> help(json.loads)
Help on function loads in module json:
loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
Deserialize ``s`` (a ``str`` instance containing a JSON
document) to a Python object.
Upvotes: 0