Python中json对象的零大小长度

时间:2015-11-25 07:45:53

标签: python json

我不确定为什么会这样,我的json文件中的长度为零。

0

我应该是这样的,

1000

我担心每个json对象之后的comma事件会导致此问题。 (我目前的json格式)

{ A:"A"},{ B:"B"),...

正确的方法是这样的

{ A:"A"} { B:"B"),...

那么如何在不删除comma的情况下计算所有长度?

我的代码

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"
},...

2 个答案:

答案 0 :(得分:2)

我认为你得到一个例外,因为逗号,你用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()

答案 1 :(得分: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 []

Mixing iteration and read methods would lose data