0

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

3 Answers 3

2

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"}}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

I know i can use json.loads(), but wich parse through the entire string and create a dictionary out of it. But in reality , there is no use for the data for the resource owner, only for external systems this data is relevant. I worry why i should convert this string to another dictionary object, and this object is very heavy in size can go up to 128KB of string data. is there a way that while serialization, just consider this as a raw Json formated string. that is what @JsonRawValue does in Java (Jackson)..Looking for any alternative like that in python
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.