python中的JSON解析给出了错误

时间:2014-02-17 07:43:53

标签: python json

我正在尝试解析一个类似于下面的json文件:

{ "results": [ 
{ "ID": "63768E9B-1D66-486A-BCDD-D3991EAFBE94", 
"Dt": "2013-08-03T13:01:26.901Z", 
"Dt_u": "2013-08-03T13:01:26.901Z", 
"obj": "enppXhI7TS" 
}, 
{ 
"ID": "63768E9B-1D66-486A-BCDD-D3991EAFBE94", 
"Dt": "2013-08-03T16:17:33.280Z",
"Dt_u": "2013-08-03T16:17:33.280Z",
"obj": "79J5z6y2UR" 
}, 
{ 
"ID": "F8B1B9FB-7BCD-47DF-89BD-241440BB6270",
"Dt": "2013-08-06T00:23:43.562Z", 
"obj": "Xf75BFtx4O",
"gender": 2,
"language": "en"
}]}

文件中还有更多条目

现在,当我尝试在python中使用JSON Parser加载此文件时,它给了我

Traceback (most recent call last):
  File "E:\test.py", line 8, in <module>
    data = json.dumps(json_data)
  File "C:\python27\lib\json\__init__.py", line 243, in dumps
    return _default_encoder.encode(obj)
File "C:\python27\lib\json\encoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)
File "C:\python27\lib\json\encoder.py", line 270, in iterencode
    return _iterencode(o, 0)
File "C:\python27\lib\json\encoder.py", line 184, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <open file 'data.json', mode 'r' at 0x00000000022E6540> is not JSON  
serializable

[退出代码1完成0.9秒]

我的代码是

import json
from pprint import pprint


json_data=open('data.json','r')

data = json.dumps(json_data)
jsondata = data["results"]

for item in jsondata:
name = item.get("ID")
json_data.close()

&LT;&LT;&LT;&LT;&LT;&LT;&GT;&GT;&GT;&GT;&GT;&GT;&GT;&GT;&GT;&GT;

import json
from pprint import pprint


json_data=open('data.json','r')

data = json.load(json_data)
jsondata = data["results"]

for item in jsondata:
name = item.get("ID")
json_data.close()

现在提供错误 - &gt;

Traceback (most recent call last):
  File "E:\test.py", line 7, in <module>
    data = json.load(json_data)
  File "C:\python27\lib\json\__init__.py", line 290, in load
    **kw)
  File "C:\python27\lib\json\__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "C:\python27\lib\json\decoder.py", line 365, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\python27\lib\json\decoder.py", line 381, in raw_decode
   obj, end = self.scan_once(s, idx)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xc2 in position 2: invalid    continuation byte
[Finished in 0.2s with exit code 1]

我知道它与某些Unicode数据有关。但我如何识别并解决它?

3 个答案:

答案 0 :(得分:1)

您正在尝试转储一个字符串,该字符串是您正在读取的文件。如果那句话对你没有意义,那是因为基础操作是荒谬的。请改为json.load()

答案 1 :(得分:0)

首先,这是您粘贴的数据中的语法错误。第17行末尾缺少一个逗号。

其次你需要调用json.load(json_data)才能从文件中加载json。

答案 2 :(得分:0)

首先,没有名为 seniorID 的键,其次你需要使用json.load(json_data)