Daniel S.
Daniel S.

Reputation: 23

How to add a character like ("," , "[" , "]") at the end of a JSON-Object

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:

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

New_File.json:

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

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.

The result should be like the New-File

Upvotes: 1

Views: 4848

Answers (4)

Rishav Sharma
Rishav Sharma

Reputation: 9

to add automatic comma between each object and add brackets in file to make it complete json just write a simple jq query

jq -s '.' file_name

Upvotes: -1

AndreyF
AndreyF

Reputation: 1838

First of all I don't think there is a way to parse it directly as JSON array. However, if your JSON objects are not nested a simple way to parse them is to split your string:

with open(YOUR_FILE) as jsons_file:
    jsons = [x.strip() + '}' for x in jsons_file.read().split('}')][:-1]

now you can dump it to file or string using json's library dump or dumps

json.dumps(jsons)

or

with open(OUT_FILE, 'w') as out_file:
    json.dump(jsons, out_file)

Upvotes: 0

Vivek Harikrishnan
Vivek Harikrishnan

Reputation: 866

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)

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

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

Upvotes: 1

user7884512
user7884512

Reputation:

Can't you do

words.replace('}','},')

This should replace all instances of '}' with a '},'

Upvotes: 0

Related Questions