我正在尝试使用json.load()方法在Python中解析包含JSON对象的一些文本文件。它适用于其中一组,但对于这一组,它不会:
{
"mapinfolist":{
"mapinfo":[
{"sku":"00028-0059","price":"38.35","percent":"50","basepercent":"50","exact":0,"match":0,"roundup":0}
,{"sku":"77826-7230","price":"4.18","percent":"60","basepercent":"60","exact":1,"match":0,"roundup":0}
,{"sku":"77827-1310","price":"2.36","percent":"60","basepercent":"60","exact":1,"match":0,"roundup":0}
,{"sku":"77827-2020","price":"2.36","percent":"60","basepercent":"60","exact":1,"match":0,"roundup":0}
,{"sku":"77827-3360","price":"2.36","percent":"60","basepercent":"60","exact":1,"match":0,"roundup":0}
,{"sku":"77827-4060","price":"2.36","percent":"60","basepercent":"60","exact":1,"match":0,"roundup":0}
,{"sku":"77827-4510","price":"2.36","percent":"60","basepercent":"60","exact":1,"match":0,"roundup":0}
,{"sku":"77827-7230","price":"2.36","percent":"60","basepercent":"60","exact":1,"match":0,"roundup":0}
],
"count":2
}
}
它位于名为' map.txt'的文件中。 - 我用open(' map.txt')打开它,然后调用json.load()。当我运行我的测试程序(test.py)时,会生成以下错误跟踪:
Traceback (most recent call last):
File "test.py", line 28, in <module>
main()
File "test.py", line 23, in main
map_list = json.load(f1)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/json/__init__.py", line 268, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/json/__init__.py", line 318, in loads
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/json/decoder.py", line 343, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/json/decoder.py", line 361, in raw_decode
raise ValueError(errmsg("Expecting value", s, err.value)) from None
ValueError: Expecting value: line 1 column 1 (char 0)
JSON对象是有效的 - 当我将它放入https://www.jsoneditoronline.org/时,它会被正确解析和显示,因此当我尝试在Python中执行此操作时,我无法确定可能阻止其工作的内容。任何建议将不胜感激。谢谢!
编辑:这是我的代码。
import json
def main():
with open('map.txt') as f1:
map_list = json.load(f1)
尝试map_list = json.loads(f1.read())
也不起作用,并给我一个几乎相同的错误跟踪。
编辑 - 已解决:
我只是将FROM.txt复制并粘贴到新的TextEdit文件map2.txt中,然后使用新文件,现在可以使用了。我直接从旧文件复制并没有做任何更改 - 唯一的区别是它是一个不同的文件。我不能为什么会这样做 - 或任何想法?我想了解可能发生的事情,以便将来可以避免这个问题。
答案 0 :(得分:0)
答案 1 :(得分:-2)
可能尝试将所有文件读取为字符串,然后使用json.loads
def yourfunc():
file = open('map.txt')
json_string = file.read()
map = json.loads(json_string)