【问题标题】:Read a JSON file containing unicode data读取包含 unicode 数据的 JSON 文件
【发布时间】:2016-12-08 04:45:58
【问题描述】:

这是我的 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

【问题讨论】:

  • 改用json.loads()

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


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    试试这个,

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

    或使用:

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

    我已经转储到 json 以重新创建问题。你可以使用json.loads

    【讨论】:

    • 这是我当前的代码; with open(jsonFile, 'rt') as fin: jsonDy = json.loads(fin.read())...但出现以下错误...Traceback (most recent call last): content = Read_json_file(eventFile) jsonDy = json.loads(fin.read()) obj, end = self.scan_once(s, idx) ValueError: Expecting property name: line 1 column 2 (char 1)
    • json.loads(fin.read().replace("\'", '"')) 你能试试这个告诉我吗?
    • 试过了....但是,得到同样的错误;暂时;我已将我的文件更改为具有有效的 JSON 内容...正如@Lex 所指出的...通过测试解决了我当前的障碍...
    • 可能对处于相同情况的某人有所帮助......尽管不确定这是否是一个优雅的解决方案。这虽然可行....json.loads(fin.read().replace("u'", '"').replace("'", '"'))
    猜你喜欢
    • 2012-11-21
    • 2014-07-21
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    • 2018-06-19
    • 2017-04-18
    • 1970-01-01
    • 2011-07-26
    相关资源
    最近更新 更多