Turn a python dict to a string with single backslash and double quotes

Viewed 924

I have a dict as follows in python

test_dict  = {'A': 'apple', 'B': 12345000, 'c': '2020-07-13 03:04:21.752566'}

And I need to format the json output as follows inclusing back slashes and comments, Back slashes and comments are not required for int values

{
   "zz":"zz",
   "xx":"x",
   "rawData":"{\"A\":\"apple\",\"B\":12345000,\"c\":\"2020-07-13 03:04:21.752566\"}"

}

I have implemented following function

def construct_raw(abc):
    start = "\"{"
    end = "}"
    delimiter = ","
    dict_len = len(abc)
    cnt = 0
    for k, v in abc.items():
        cnt = cnt + 1
        if type(v) is str:
            n = "\\\"" + v + "\\\""
        else:
            n = str(v)
        start = start + "\\\"" + k + "\\\"" + ":" + n
        if cnt != dict_len:
            start = start + delimiter

    start = start + end + "\""
    return start

This produced following output for rawData

"{\\"A\\":\\"apple\\",\\"B\\":12345000,\\"c\\":\\"2020-07-13 03:04:21.752566\\"}"

But this will results double back slash in the string How to fix this issue?

3 Answers

Use json.dumps(test_dict)

In [123]: a = {}

In [124]: a["zz"] = "zz"

In [125]: a["xx"] = "x"

In [126]: a["rawData"] = json.dumps(test_dict)

In [127]: with open("a.json","w") as f:
     ...:     json.dump(a,f)
     ...:

When you open a.json you will get the backslash

{"zz": "zz", "xx": "x", "rawData": "{\"A\": \"apple\", \"B\": 12345000, \"c\": \"2020-07-13 03:04:21.752566\"}"}
test_dict = {"A": "apple", "B": 12345000, "c": "2020-07-13 03:04:21.752566"}
import json

result = json.dumps(test_dict).replace('"', '\\"')

Output:

{\"A\": \"apple\", \"B\": 12345000, \"c\": \"2020-07-13 03:04:21.752566\"}

Try this:

def construct_raw(abc):
    start = "\"{"
    end = "}"
    delimiter = ","
    dict_len = len(abc)
    cnt = 0
    for k, v in abc.items():
        cnt = cnt + 1
        if type(v) is str:
            n = "\"" + v + "\""
        else:
            n = str(v)
        start = start + "\"" + k + "\"" + ":" + n
        if cnt != dict_len:
            start = start + delimiter

    start = start + end + "\""
    return start

or this:

test_dict  = {'A': 'apple', 'B': 12345000, 'c': '2020-07-13 03:04:21.752566'}
str_dict = '{'
for k, v in test_dict.keys(), test_dict.values():
    if isinstance(k, str):
        str_dict += '\"k\"'
    elif isinstance(k, int):
        str_dict += 'k'
    str_dict += ":"
    if isinstance(v, str):
        str_dict += '\"v\"'
    elif isinstance(k, int):
        str_dict += 'v'
    str_dict += ','
if str_dict != '{':
    str_dict = str_dict[:-1]
str_dict += '}'
Related