如何使用python pandas 读取json文件? [英] How to read json file using python pandas?

查看:133
本文介绍了如何使用python pandas 读取json文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用python熊猫读取json文件.文件的每一行都是JSON中的完整对象.

I want to read json file using python pandas. Each line of the file is a complete object in JSON.

我正在使用以下版本-

python:2.7.6

python : 2.7.6

熊猫:1.19.1

json文件-

{"id":"111","p_id":"55","name":"aaa","notes":"","childs":[]}
{"id":"222","p_id":"56","name":"bbb","notes":"","childs":[]}
{"id":"333","p_id":"75","name":"ccc","notes":"","childs":[]}
{"id":"444","p_id":"76","name":"ddd","notes":"","childs":["abc","efg","pqr"
,"rtu"]}

我正在使用以下代码读取json文件-

I'm using below code to read json file-

df = pd.read_json("temp.txt", lines = True)
print df

问题是,在json文件中,"childs"键包含一个未知索引数组,并且在"\ n"之间可用.因此,如果我在上面的代码上运行,我会得到 ValueError:预期的对象或值,但是如果我在"pqr"之后删除了可用的"\ n",我的代码就会起作用.

The problem is, in json file "childs" key contains a array of not known indexes and in between "\n" is available. so if I run above code I'm getting ValueError: Expected object or value but if I remove "\n" available after "pqr" my code gets work.

我不想从数据中删除可用的"\ n".我想在我的代码中处理这个问题.我只想使用python pandas而不是python json库来很好地处理数据.

I don't want to remove available "\n" from my data. I want to handle this within my code. I want to use python pandas only instead of python json libraries for handling data in good manner.

我如何仅使用python pandas并处理此类文件?

How I can make use of python pandas only and handle this type of file?

推荐答案

首先使用 JSON验证器检查它是否为有效的json文件或不使用网站

文件为有效json格式后,您可以使用以下代码将其读取为数据框

once the file is in valid json format you can use the below code to read it as dataframe

with open("training.json") as datafile:
    data = json.load(datafile)
dataframe = pd.DataFrame(data)

希望这会有所帮助.

这篇关于如何使用python pandas 读取json文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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