Python 如何编辑或访问非标准JSON文件';s值是否正确
我有一个非标准格式的JSON文件,如下所示:Python 如何编辑或访问非标准JSON文件';s值是否正确,python,json,parsing,Python,Json,Parsing,我有一个非标准格式的JSON文件,如下所示: { "color": "black", "category": "hue", "type": "primary" } { "color": "white", "category": "value", "type": "idk" } { "color": "red", "category": "hue", "type": "primary" } [ { "
{
"color": "black",
"category": "hue",
"type": "primary"
}
{
"color": "white",
"category": "value",
"type": "idk"
}
{
"color": "red",
"category": "hue",
"type": "primary"
}
[
{
"color": "black",
"category": "hue",
"type": "primary"
},
{
"color": "white",
"category": "value",
"type": "idk"
},
{
"color": "red",
"category": "hue",
"type": "primary"
},
]
但它有超过10000个条目以这种方式格式化。我必须访问每个单独部分的颜色和类型,并为每个部分创建一个字符串,表示“type color”,如“primary black”
我想用Python编辑文件,使其看起来像这样:
{
"color": "black",
"category": "hue",
"type": "primary"
}
{
"color": "white",
"category": "value",
"type": "idk"
}
{
"color": "red",
"category": "hue",
"type": "primary"
}
[
{
"color": "black",
"category": "hue",
"type": "primary"
},
{
"color": "white",
"category": "value",
"type": "idk"
},
{
"color": "red",
"category": "hue",
"type": "primary"
},
]
因此,我可以使用[]访问值,并对所有值使用for循环。我该怎么做?有没有比编辑json文件更好的方法呢?文件是json还是不是json,而您给出的示例文件不是。将其称为“非标准JSON”是不准确和令人困惑的 也就是说,下面是我将如何使用Python将该文件转换为真正的JSON的概要:
Open a new file for writing.
Write "[" to the output file.
Open your existing file for reading.
For each line in the file:
Write that line to the output file.
If that line is "}", but it is not the last line, also write a comma.
Write ] to the output file.
您可以使用
str.format
In [341]: with open('f.json', 'r') as f:
...: string = f.read()
...:
In [342]: string
Out[342]: '{\n "color": "black",\n "category": "hue",\n "type": "primary"\n}\n{\n "color": "white",\n "category": "value",\n "type": "idk"\n}\n{\n "color": "red",\n "category": "hue",\n "type": "primary"\n}\n'
In [343]: string = string.replace('}','},') # Must split each '{}' with a comma
In [344]: string
Out[344]: '{\n "color": "black",\n "category": "hue",\n "type": "primary"\n},\n{\n "color": "white",\n "category": "value",\n "type": "idk"\n},\n{\n "color": "red",\n "category": "hue",\n "type": "primary"\n},\n'
In [345]: string = string[:-2] # Get rid of the trailing comma
In [346]: string
Out[346]: '{\n "color": "black",\n "category": "hue",\n "type": "primary"\n},\n{\n "color": "white",\n "category": "value",\n "type": "idk"\n},\n{\n "color": "red",\n "category": "hue",\n "type": "primary"\n}'
In [347]: json.loads('[{0}]'.format(string))
Out[347]:
[{'color': 'black', 'category': 'hue', 'type': 'primary'},
{'color': 'white', 'category': 'value', 'type': 'idk'},
{'color': 'red', 'category': 'hue', 'type': 'primary'}]
你真的不需要Python
sed'1s/^/[/;$!/}/},/;$s/$/]/'file>file.json
上述代码实际上修复了伪代码的错误;如果这是最后一行,请不要加逗号。Soo还@tripleee感谢您的错误发现!我已经编辑了我的答案。谢谢,我以前从未使用过JSON文件,提供该文件的人说它是JSON“_(ツ)_/''但我应该知道。@tripleee您提供的链接在每行中添加了一个逗号,因此它与我的代码不兼容。如果有办法编辑它,只在以}结尾的行中添加逗号,那将非常有用