[英]Python read a multiline file and convert to map
I have a file which has the content as below:我有一个文件,其内容如下:
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
In python, I want to read this file and store as a map (key-value pair).在 python 中,我想读取此文件并存储为 map(键值对)。 I tried to use json, but it is giving some parsing error (
\n
is being added at the end of each line)我尝试使用 json,但它给出了一些解析错误(在每行的末尾添加了
\n
)
Here value1
, value2
, value3
can be a multiline string.这里
value1
, value2
, value3
可以是多行字符串。 As below:如下:
{
"key1": "value1
Jsjsjsj",
"key2": "value2",
"key3": "value3"
}
Let me know how to do it.让我知道该怎么做。 Thanks
谢谢
It looks like a usual JSON, so just use json
module它看起来像一个普通的 JSON,所以只需使用
json
模块
import json
with open("file.txt") as fp:
document = json.load(fp)
print(document)
To support multiline, you can use multiline
package:要支持多行,您可以使用
multiline
package:
$ pip install multiline
import multiline
with open("file.txt") as fp:
document = multiline.load(fp, multiline=True)
print(document)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.