2

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.

2
  • stackoverflow.com/questions/25242262/… -- possible solution Commented Apr 13, 2020 at 16:06
  • @Rajat Mishra - It didn't worked for me as I cannot convert string data to dictionary. Is there any way I can create variables with raw string as its values? Commented Apr 13, 2020 at 16:09

3 Answers 3

2

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

3 Comments

I cannot declare string as dictionary.Data is coming as string.
In that case, use the json.loads() to convert dictionary string to dictionary.
Thanks I used json.loads() with strict flag and it worked!
0

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

Comments

0

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

1 Comment

How is this module better than using the built in json python module?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.