读取包含unicode数据的JSON文件

时间:2016-08-02 17:36:37

标签: python json python-2.7 unicode python-unicode

以下是我的JSON文件的内容

cat ./myfile.json

{u'Records': [{u'eventVersion': u'2.0', }]}

如何阅读此JSON文件?

我尝试使用以下代码阅读文件

def Read_json_file(jsonFile):
   jsonDy = {}
   if os.path.exists(jsonFile):
      with open(jsonFile, 'rt') as fin:
         jsonDy = json.load(fin)
   else:
      print("JSON file not available ->",
                                 jsonFile)
      sys.exit(1)
   print("jsonDy -> ", jsonDy)

但是收到以下错误,

Traceback (most recent call last):
  File "a.py", line 125, in <module>
    Main()
  File "a.py", line 18, in Main
    content = Read_json_file(eventFile)
  File "a.py", line 44, in Read_json_file
    jsonDy = json.load(fin)
  File "/usr/lib64/python2.7/json/__init__.py", line 290, in load
    **kw)
  File "/usr/lib64/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/usr/lib64/python2.7/json/decoder.py", line 365, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib64/python2.7/json/decoder.py", line 381, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)

我的理解是u'代表unicode符号,但不确定如何阅读此文件

PS:我使用的是Python 2.7

2 个答案:

答案 0 :(得分:3)

这不是一个有效的JSON结构。它是Python数据结构的字符串表示。适当的JSON结构是:

{"Records": [{"eventVersion": "2.0"}]}

看起来有些东西是用json.loads的输出而不是json.dumps编写JSON。

答案 1 :(得分:1)

试试这个,

update EV.Test_Result 
set waived = 1
from EV.Test_Result
join EV.Test_Result as t on EV.Test_Result.test_row_id = t.test_row_id and EV.Test_Result.start_time < t.start_time and t.device_id = 1219 and t.waived = 0

或使用:

import simplejson as json
w = json.dumps({u'Records': [{u'eventVersion': u'2.0', }]})
print json.loads(w)

我已经转发给json来重新创建这个问题。您可以使用import json w = json.dumps({u'Records': [{u'eventVersion': u'2.0', }]}) print json.loads(w)