【发布时间】:2018-03-27 12:17:28
【问题描述】:
我有一个以下格式的 JSON 文件 -
注意 1 和 2 之后的字符(等)表示不带双引号的字符串
{
"Apparel": {
"XX": {
"1": YY,
"2": ZZ
},
"TT": {
"1":TTT,
"2":TTT,
"3": TTT,
"4": TTT
},
"XXX": {
"1":XXX,
"2":XXX
},
"RRR": {
"1":RRR,
"2":RRR
},
"AAA": {
"1":AAA,
"2":AAA,
"3":AAA
},
}
....
等等。
现在我知道文件格式不正确(由于设计或某些 idk 原因,文件以这种方式保存)并且将其与 Python3 中的标准 json 模块一起使用会产生解码错误,但我被告知要按原样使用文件。这意味着任何问题,我将不得不对我的代码进行排序。我需要从每个标题中选择1 之后的值,然后从每个标题中选择2 中的值等等。
目前我正在使用此代码来读取文件 -
import json
with open("brand_config.json") as json_file:
json_data = json.load(json_file)
test = (json_data["apparel"]["biba"])
print (test)
这段代码给出了这个错误-
Traceback (most recent call last):
File "reader.py", line 4, in <module>
json_data = json.load(json_file)
File "/usr/lib/python3.5/json/__init__.py", line 268, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "/usr/lib/python3.5/json/__init__.py", line 319, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.5/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.5/json/decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 4 column 9 (char 36)
如何在不更改 JSON 文件中的任何内容的情况下读取所需的值。
【问题讨论】:
-
你能发布你的原始 JSON。看起来 JSON 无效。
-
你的问题有点缺乏细节。您是否像这样显示 ZZ 和 YY 是因为您的文件中有未引用的字符串,这就是 JSON 无效的原因?
-
正是我的意思... JSON 无效。我发布的文件与原始 JSON 格式完全相同,只是我更改了值
-
解决方案:使用有效的 JSON。 (或者不要假装它是 JSON 并编写自己的解析器)
-
@DanielRoseman 问题已编辑。请立即查看
标签: python json io python-3.5