在python中创建有效的json对象 [英] create valid json object in python

查看:78
本文介绍了在python中创建有效的json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每行都是有效的JSON,但我需要将文件作为一个整体才能有效.

Each line is valid JSON, but I need the file as a whole to be valid JSON.

我有一些数据是从Web服务聚合并转储到文件中的,所以它是JSON格式的,但不是有效的JSON,因此无法以JSON文件可以简单直观的方式进行处理-从而在脖子上造成了严重的疼痛,它看起来(或多或少)是这样的:

I have some data which is aggregated from a web service and dumped to a file, so it's JSON-eaque, but not valid JSON, so it can't be processed in the simple and intuitive way that JSON files can - thereby consituting a major pain in the neck, it looks (more or less) like this:

{"record":"value0","block":"0x79"} 
{"record":"value1","block":"0x80"} 

我一直试图将其重新解释为有效的JSON,我的最新尝试如下:

I've been trying to reinterpret it as valid JSON, my latest attempt looks like this:

with open('toy.json') as inpt:
    lines = []
    for line in inpt:
        if line.startswith('{'):  # block starts
            lines.append(line) 

但是,正如您可能会从我提出这个问题(这行不通)这一事实中可以推断出,关于如何解决该问题的任何想法吗?

However, as you can likely deduce by the fact that I'm posing this question- that doesn't work- any ideas about how I might tackle this problem?

尝试过:

with open('toy_two.json', 'rb') as inpt:

    lines = [json.loads(line) for line in inpt] 

print(lines['record'])

但出现以下错误:

Traceback (most recent call last):
  File "json-ifier.py", line 38, in <module>
    print(lines['record'])
TypeError: list indices must be integers, not str

理想情况下,我希望与普通JSON(即data['value']

Ideally I'd like to interact with it as I can with normal JSON, i.e. data['value']

EDIT II

with open('transactions000000000029.json', 'rb') as inpt:

    lines = [json.loads(line) for line in inpt]

    for line in lines: 
        records = [item['hash'] for item in lines]
    for item in records: 
        print item

推荐答案

这看起来像是我最近正在使用的NDJSON.规范是此处,我不确定它是否有用.以下工作正常吗?

This looks like NDJSON that I've been working with recently. The specification is here and I'm not sure of its usefulness. Does the following work?

with open('the file.json', 'rb') as infile:
    data = infile.readlines()
    data = [json.loads(item.replace('\n', '')) for item in data] 

这应该给您词典列表.

这篇关于在python中创建有效的json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆