处理我的JSON文件时Python有什么问题? [英] What is the issue with Python while processing my JSON file?

查看:76
本文介绍了处理我的JSON文件时Python有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用python从json文件中删除第一个键和值.在运行程序时,我遇到了错误,它们被提及如下:

I have tried to remove the first key and value from a json file using python. While running the program, I came across error, they are mentioned as follows:

import json
with open('testing') as json_data:
    data = json.load(json_data)
    for element in data:
        del element['url']

错误:

Traceback (most recent call last):
  File "p.py", line 3, in <module>
    data = json.load(json_data)
  File "/usr/lib/python3.5/json/__init__.py", line 268, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "/usr/lib/python3.5/json/__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.5/json/decoder.py", line 342, in decode
    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 180)

文件输入如下:

{"url":"example.com","original_url":"http://example.com","text":"blah...blah"...}
{"url":"example1.com","original_url":"http://example1.com","text":"blah...blah"...}
.
.
.
.
{"url":"exampleN.com","original_url":"http://exampleN.com","text":"blah...blah"...}

我不知道为什么会出现这个问题?

I don't know why is this problem occurring?

推荐答案

您必须逐行读取文件,因为它是json数据行而不是有效的json结构

you have to read the file line by line, since it's rather lines of json data than valid json structure

这是我的逐行建议

import json
data = []
with open('testing') as f:
    for json_data in f:
       element = json.loads(json_data)  # load from current line as string
       del element['url']
       data.append(element)

在这种情况下,有效的json将是

Valid json would be in that case:

[{"url":"example.com","original_url":"http://example.com","text":"blah...blah"...},
{"url":"example1.com","original_url":"http://example1.com","text":"blah...blah"...}]

这篇关于处理我的JSON文件时Python有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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