无法在Python中读取JSON文件

时间:2012-12-03 00:01:17

标签: python json

我试图从JSON文件中读取数据,但是我遇到了奇怪的错误,并且不知道它意味着什么。我试着谷歌搜索它,但它没有帮助。我收到以下错误:

Traceback (most recent call last):
  File "items_uploader.py", line 40, in <module>
    main()
  File "items_uploader.py", line 16, in main
    LoadItemsData(settings['items_filename'])
  File "items_uploader.py", line 36, in LoadItemsData
    data = json.load(json_data)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 278, in load
    **kw)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 326, in loads
    return _default_decoder.decode(s)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting , delimiter: line 8 column 397 (char 3064)

代码本身非常简单:

import socket
import MySQLdb
from ConfigParser import SafeConfigParser
import json
from pprint import pprint

def main():
    settings = GetSettings()
    LoadItemsData(settings['items_filename'])
    return

def GetSettings():
    settings = {}
    parser = SafeConfigParser()
    parser.read('settings.yaml')
    settings['items_filename'] =  parser.get('files', 'items_filename')
    return settings

def LoadItemsData(filename):
    json_data=open(filename)
    data = json.load(json_data)
    return data

if __name__ == '__main__':
    main()

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:3)

确保您的JSON数据格式有效,一个额外的字符弄乱python解析器。要测试您的JSON数据,请转到here,确保您能够以正确的格式查看它。

例如,如果我有

JSON_data ='{"c":[{"xy":{"xstart":0,"xend":5,"ystart":1,"yend":5},"names":["D","T","O","H","L","C",],"co":["rgb(0,0,128)"]}],"Values":{"D":["11/30/2012"],"T":["09:44:00"],"O":["5848.40"],"H":["5848.40"],"L":["5847.45"],"C":["5848.40"]}}'

,之后的C(此处为["D","T","O","H","L","C",])会显示错误。因此,请确保您的数据格式正确,并且没有不必要的字符。

希望这有帮助。