如何在JSON对象的末尾添加字符(“,","[",“]") [英] How to add a character like ("," , "[" , "]") at the end of a JSON-Object

查看:248
本文介绍了如何在JSON对象的末尾添加字符(“,","[",“]")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python脚本,可以使文件带有无效的JSON. 现在,我要操作此JSON文件,通过在每个对象之间添加逗号(在文件的开头为'[',在结尾为']')使其成为有效的JSON文件. 有没有一种方法可以单独使用JSON来实现,还是我必须找到其他读取和写入函数的方法?

I have a Python-script that makes an File with invalid JSON. Now I want to manipulate this JSON-File so it becomes a valid JSON-file by adding a comma between every object, at the beginning of the File a '[' and at the end a ']'. Is there a way to make this with JSON alone or do i have to find a way with other read and write functions?

Exsample_File.json:

Exsample_File.json:

    {
    "firstName": "Bidhan",
    "lastName": "Chatterjee",
    "age": 40,
    "email":"bidhan@example.com"
    }
    {
    "firstName": "hanbid",
    "lastName": "jeeChatter",
    "age": 10,
    "email":"example@bidhan.com"
    }
     .... 
    n times

New_File.json:

New_File.json:

    [
    {
    "firstName": "Bidhan",
    "lastName": "Chatterjee",
    "age": 40,
    "email":"bidhan@example.com"
    },
    {
    "firstName": "hanbid",
    "lastName": "jeeChatter",
    "age": 10,
    "email":"example@bidhan.com"
    },
     .... 
    n times
    ]

这是制作此JSON文件的功能.我不想触摸生成str的其他代码.

This is the function that makes this JSON-File. I dont want to touch the other code where the str is generated.

data = json.loads(str)
    with open('Example_File.json','ab')as outfile:
        json.dump(data, outfile, indent=2)

到目前为止,我还没有解决这个问题的想法.因此,没有代码示例会有所帮助.

So far i dont have an idea to solve this problem. so there is no code sample that would help.

结果应该类似于"New-File"

The result should be like the New-File

推荐答案

您可能必须将内容读取为字符串,对其进行操作并以JSON格式加载.像这样的东西

You may have to read the content as string, manipulate it and load as JSON. Something like this,

import json

with open('Example.json','r') as f:
  data = f.read()

data = "[" + data.replace("}", "},", data.count("}")-1) + "]"
json_data = json.loads(data)

似乎您的数据具有以0开头的数字,因此您可能会以"ValueError"异常结束.您可以从中了解为什么处理JSON如果整数以0开头,则无效

It seems your data has numbers begins with 0, so you may ended up with an exception "ValueError". You may refer how to deal the issue from Why is JSON invalid if an integer begins with 0

注意:我从"Example.json"中手动删除了0

Note: I manually removed 0 from "Example.json"

这篇关于如何在JSON对象的末尾添加字符(“,","[",“]")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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