简体   繁体   中英

Python : How to write json formatted string in json file

I have a requirement where I have to write some JSON string in a file.

For example, I have below string in

My python code:

 S = '''{
"K1": "v1",
"K2" : "\nv2"
}'''

When I try to write it in json file using json.dumps(s) it is getting written to a file like below:

"{\"k1\" : \"v1\",\"k2\" : \"\\nv2\"}"

Whereas I need it to be like:

 {
"K1": "v1",
"K2" : "\nv2"
}

In json file.

I am able to achieve this if I declare my string as raw string preceding with r but In the actual scenario I cannot declare a raw string as I am getting the string value in python variable.

Note: I am having multiple escape sequences in my json string value like given in value for key k2 in the above json structure.

Will really appreciate it if anyone helps me to generate a proper json file with required json format.Thanks in advance.

Declare your variable as

S = {
"K1": "v1",
"K2" : "\nv2"
}

Then it would work. For example:

In [16]: s
Out[16]: {'K1': 'v1', 'K2': '\nv2'}

In [17]: st = json.dumps(s)

In [18]: st
Out[18]: '{"K1": "v1", "K2": "\\nv2"}'

In [19]: s1 = '''{
    ...: "K1": "v1",
    ...: "K2" : "\nv2"
    ...: }'''

In [20]: st1 = json.dumps(s1)

In [21]: st1
Out[21]: '"{\\n\\"K1\\": \\"v1\\",\\n\\"K2\\" : \\"\\nv2\\"\\n}"'

Update : If your data is coming as string, first convert it into dictionary using json.loads(). For example:

In [24]: st
Out[24]: '{"K1": "v1", "K2": "\\nv2"}'

In [25]: json.loads(st)
Out[25]: {'K1': 'v1', 'K2': '\nv2'}

In [26]: json.dumps(json.loads(st))
Out[26]: '{"K1": "v1", "K2": "\\nv2"}'

I get it working for my specific requirement using below modifications python3.6 code:

py_string = '''{ "k1":"v1","k2":"\nv2"}'''
valid_json_string = json.dumps(json.loads(py_string ,strict=False))
with open('test.json', 'w') as outfile:
     json.dump(valid_json_string, outfile)

With this lines of code I was able to write this json string in json file without having escaped double quotes and strings.

Basically, when we paste the json contents directly to assign it to python string,Python will not allow the json valid control characters in string.python string will escape the special control characters like \n will treat as newline.

So to allow it in python string json.loads() supports "strict" flag. If strict is false (True is the default), then control characters will be allowed inside strings. Control characters in this context are those with character codes in the 0–31 range, including '\t' (tab), '\n', '\r' and '\0'.

For more info - https://docs.python.org/3/library/json.html

If you want an easy way to do it you can use jsonwriter
for example:

# pip install jsonwriter
from jsonwriter import file

file = file('yourfilename.json', autosave=True)

file.set('K1', 'v1')
file.set('K2', '\nv2')
# And it will be saved automatically

for more info checkout jsonwriter docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM