pasing json时的syntaxerror

时间:2017-07-22 17:01:20

标签: python json syntax-error

我想从文本文件中创建json,并使列表值为['ids']

{"previous_cursor": 0, "previous_cursor_str": "0", "next_cursor": 1351473067174597097, "ids": [250718906, 66612533], "next_cursor_str": "1351473067174597097"} {"previous_cursor": -1351352880715992572, "previous_cursor_str": "-1351352880715992572", "next_cursor": 0, "ids": [113030689, 22020972], "next_cursor_str": "0"}

我的代码

import json

f = open('22580877','r')
data = f.read()
datalist = data.split('\n')
idslist = []

for i in datalist:
    datadic = eval(i)
    print(datadic['ids'])
    idslist.extend(datadic['ids'])
    datadic = {}

for j in idslist:
    print(j)

f.close()

错误消息是

Traceback (most recent call last):
  File "test.py", line 11, in <module>
    datadic = eval(i)
  File "<string>", line 0

    ^
SyntaxError: unexpected EOF while parsing

我无法在代码中找到我的语法错误。请帮帮我!

1 个答案:

答案 0 :(得分:0)

听起来你已经在文件的每一行上交了一个带有jsonified字符串的文件。从您的错误消息我有点想知道您的文件是否已损坏或未按您认为的那样格式化。但是,如果我已经完成了你提供的任务,我会做这样的事情......

import json, traceback
idslist = []
with open('22580877', 'r') as f:
    data = f.read()
    datalist = data.split('\n')
    for idx, json_string in enumerate(datalist):
    try:
        json_obj = json.loads(json_string)
        idslist.extend(json_obj['ids'])
    except:
        print "bad json on line {} with traceback:\n{}".format(idx+1, traceback.format_exc())

for id in idslist:
    print(id)