Python中json对象的零大小长度
我不确定为什么会发生这种情况,我的json文件长度为零Python中json对象的零大小长度,python,json,Python,Json,我不确定为什么会发生这种情况,我的json文件长度为零 0 我不应该是这样的 1000 恐怕每个json对象后面的逗号会导致这个问题。(我当前的json格式) 正确的方法是这样的 { A:"A"} { B:"B"),... 那么,如何在不删除逗号的情况下计算所有长度呢 我的代码 import json githubusers_data_path = 'githubusers.json' githubusers_data = [] githubusers_file = open(gith
0
我不应该是这样的
1000
恐怕每个json对象后面的逗号
会导致这个问题。(我当前的json格式)
正确的方法是这样的
{ A:"A"} { B:"B"),...
那么,如何在不删除逗号的情况下计算所有长度呢
我的代码
import json
githubusers_data_path = 'githubusers.json'
githubusers_data = []
githubusers_file = open(githubusers_data_path, "r")
for line in githubusers_file:
try:
data = json.loads(line)
githubusers_data.append(data)
except:
continue
print len(githubusers_data)
样品
{
"login": "datomnurdin"
}, {
"login": "ejamesc"
},...
我想你得到了一个异常,你用try-except来抑制它,因为逗号。 一种解决方案是首先将文件转换为字符串,在字符串周围粘贴“[”和“]”,将其转换为有效的
json
格式,然后使用json.loads
转换字符串
import json
githubusers_data_path = 'githubusers.json'
githubusers_file = open(githubusers_data_path, "r")
githubusers_string = ''.join(line for line in githubusers_file)
githubusers_string = '[{}]'.format(githubusers_string)
githubusers_data = json.loads(githubusers_string)
print len(githubusers_data)
githubusers_file.close()
您的代码中有一个异常:
import json
githubusers_data_path = 'githubusers.json'
githubusers_data = []
githubusers_file = open(githubusers_data_path, "r")
for line in githubusers_file:
try:
data = json.load(githubusers_file) # exception from here
githubusers_data.append(data)
except Exception, e:
print e
print len(githubusers_data) # so githubusers_data is always []
我不知道您想做什么,但是您的代码在
data=json.loads(line)
上失败了。这是因为您逐行读取文件,并且没有一行{
,“login”:“datomnurdin”
,},{
,等等是有效的json。我想您应该执行数据=json.load(githubusers\u文件)
(注意“load”中没有“s”)。通过@freakish已测试来验证您的json是否有效。长度仍然为0。@Kamehameha有效101%。您发布的示例json不是有效的json。我已运行了它(显然删除了点)。您的建议我得到了混合迭代和读取方法,这将丢失数据错误消息。但长度仍然为0。
import json
githubusers_data_path = 'githubusers.json'
githubusers_data = []
githubusers_file = open(githubusers_data_path, "r")
for line in githubusers_file:
try:
data = json.load(githubusers_file) # exception from here
githubusers_data.append(data)
except Exception, e:
print e
print len(githubusers_data) # so githubusers_data is always []