2013-02-21 38 views
0

我加載在包含在一個文本文件中的以下JSON錯誤:裝載在JSON文件給在python

{ 
"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 
} ]} 

然後我把這個文件在同一目錄蟒蛇文件,將打開它,並使用下面的代碼:

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文件錯誤或在我的代碼錯誤?

+2

的代碼是完全符合上述 – 2013-02-21 17:03:33

+0

數據文件的工作一個公平的想法,我創建一個文本文件名爲json.txt然後複製/粘貼你的代碼我的翻譯並且它工作得很好 – 2013-02-21 17:08:13

回答

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])) 
+0

爲什麼當錯誤在第1行而不是第2行時,它被讀取(2)[1]'? – 2014-06-19 18:37:10

+0

找到'冒犯性格'後應該怎麼辦? – user2441441 2015-03-09 16:13:52