简体   繁体   English

Python:如何在 json 文件中写入 json 格式的字符串

[英]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.我有一个要求,我必须在文件中写入一些JSON字符串。

For example, I have below string in例如,我有以下字符串

My python code:我的 python 代码:

 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:当我尝试使用 json.dumps(s) 将其写入 json 文件时,它被写入如下文件:

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

Whereas I need it to be like:而我需要它是这样的:

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

In json file.在 json 文件中。

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.如果我将字符串声明为在 r 之前的原始字符串,则可以实现此目的,但在实际情况下,我无法声明原始字符串,因为我在 python 变量中获取字符串值。

Note: I am having multiple escape sequences in my json string value like given in value for key k2 in the above json structure.注意:我的 json 字符串值中有多个转义序列,如上述 json 结构中键 k2 的值中给出的值。

Will really appreciate it if anyone helps me to generate a proper json file with required json format.Thanks in advance.如果有人帮助我生成具有所需 json 格式的正确 json 文件,我将不胜感激。提前致谢。

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().更新:如果您的数据以字符串形式出现,请首先使用 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:我使用以下修改 python3.6 代码让它满足我的特定要求:

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.使用这行代码,我能够在 json 文件中编写这个 json 字符串,而无需转义双引号和字符串。

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. 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.所以要在 python 字符串中允许它 json.loads() 支持“严格”标志。 If strict is false (True is the default), then control characters will be allowed inside strings.如果 strict 为 false(默认为 True),则字符串中将允许使用控制字符。 Control characters in this context are those with character codes in the 0–31 range, including '\t' (tab), '\n', '\r' and '\0'.此上下文中的控制字符是字符代码在 0-31 范围内的字符,包括“\t”(制表符)、“\n”、“\r”和“\0”。

For more info - https://docs.python.org/3/library/json.html欲了解更多信息 - https://docs.python.org/3/library/json.html

If you want an easy way to do it you can use jsonwriter如果你想要一个简单的方法,你可以使用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有关更多信息,请查看 jsonwriter文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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