Home > Mobile >  Python: Bytes to string giving escape characters
Python: Bytes to string giving escape characters

Time:12-02

rmsg variable is bytes. Value is:

rmsg = [{"Id": "A1", "status": "P", "message": ""},
        {"Id": "A2", "status": "F", "message": ""}]

I want to convert it to string so as to pass it to JSON message. I am using below command to convert it to string.

rmsg = rmsg.decode("utf-8") 

Using below command to create JSON:

rjson = {"Response Message": rmsg}

JSON message=

{
    "Response Message": "[{\"Id\": \"A1\", \"status\": \"P\", \"message\": \"\"}, {
\"Id\": \"A2\", \"status\": \"F\", \"message\": \"\"}]\n"
}

But Im getting escape character: \n at the end. I dont want to use strip command to remove it. Any other ways to pass bytes to JSON string without dealing with escape chararcters?

CodePudding user response:

In case you need to keep the JSON as a string, you can do the next:

rmsg = json.dumps(json.loads(rmsg.decode('utf-8'))

It will load data from JSON string and then dump it again to a string, but in one line, so no \ns etc.

But probably what you really want is to have the JSON stored as a dict/lists. In this case, you can do the next:

rmsg = json.loads(rmsg.decode('utf-8')
rjson = {"Response Message": rmsg)

Update: In case the original rmsg can contain a valid JSON or just a string, you should handle this (through exceptions handling). For example:

rmsg = rmgs.decode('utf-8')

try:
    rmgs = json.loads(rmsg)
except JSONDecodeError:
    pass

# ...
  • Related