Python中json对象的零大小长度

2024-05-20 00:37:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我不知道为什么会这样,我的json文件中没有长度。在

0

我应该是这样的

^{pr2}$

恐怕每个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"
},...

Tags: 文件path对象方法代码jsondata格式
2条回答

我想你得到了一个例外,你用try来抑制,除了,因为逗号。 一种解决方案是先将文件转换为字符串,在字符串周围加上“[”和“]”将其转换为有效的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 []

Mixing iteration and read methods would lose data

相关问题 更多 >