0

我正在加载包含在文本文件中的以下 json:

{
"data sources" : [
"http://www.gcmap.com/" 
] ,
"metros" : [
{
"code" : "SCL" ,
"name" : "Santiago" ,
"country" : "CL" ,
"continent" : "South America" ,
"timezone" : -4 ,
"coordinates" : {"S" : 33, "W" : 71} ,
"population" : 6000000 ,
"region" : 1
} , {
"code" : "LIM" ,
"name" : "Lima" ,
"country" : "PE" ,
"continent" : "South America" ,
"timezone" : -5 ,
"coordinates" : {"S" : 12, "W" : 77} ,
"population" : 9050000 ,
"region" : 1
} ]}

然后我将此文件与将打开它的 python 文件放在同一目录中,并使用以下代码:

import json

json_file = open('json.txt')
data = json.load(json_file)
json_file.close()

print (data)

然而,这给了我一个错误:

Traceback (most recent call last):
  File "/Users/tylerharrington/Desktop/workspace/Assignment2/src/cs242assignment2/UserInterface.py", line 11, in <module>
    data = json.load(json_file)
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/json/__init__.py", line 264, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/json/__init__.py", line 309, in loads
    return _default_decoder.decode(s)
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/json/decoder.py", line 352, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/json/decoder.py", line 368, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting property name enclosed in double quotes: line 1 column 1 (char 1)

这是否表明 python 文件有错误或我的代码中有错误?

4

1 回答 1

0
Expecting property name enclosed in double quotes: line 1 column 1 (char 1)

您的文件可能在左大括号后的第一行有一些无效字符{

转储文件od以检查文件内容或在 Windows 中使用十六进制编辑器检查文件

或者只需使用您的文件内容运行以下代码片段

with open('json.txt') as fin:
    for line in fin:
        print [hex(ord(e)) for e in line]

这将使您对冒犯的角色有一个公平的认识

或者只是

hex(ord(open('test.txt').read(2)[1]))
于 2013-02-21T17:06:05.130 回答