Yavor Stoychev
Yavor Stoychev

Reputation: 33

Add commas to list of JSON object

I have text file who contains a list of objects.

{ a:"1", b:"2", c: "3"}{ a:"1", b:"2", c: "3"}{ a:"1", b:"2", c: "3"}

I want to make it valid Json file. For instanse:

[{ a:"1", b:"2", c: "3"},{ a:"1", b:"2", c: "3"},{ a:"1", b:"2", c: "3"}]

The file is very big - 600mb. I need to do this with languages who can change files. I tried to find solution but I couldn't.

Upvotes: 3

Views: 10887

Answers (5)

Jhon Bernal
Jhon Bernal

Reputation: 21

Hello I saw this help can serve as a contribution. inside the first def comma_json add; and the structure_json adds [] to everything

def comma_json():

with open("file1.json", "r+") as f:
    old = f.read()
    f.seek(0)  # rewind
    f.write(old.replace('}{', '},{'))
    f.close

def structure_json():
  with open("file1.json", "r+") as f:
    old = f.read()
   with open("file2.json", "w") as r:
    tmps = '[' + str(old) + ']'
    json_string = json.loads(tmps)

    json.dump(json_string, r, indent=2)
    f.close

Upvotes: 1

orangeInk
orangeInk

Reputation: 1410

A sloppy but simple solution in Python:

import json
tmp = '{ "a":"1", "b":"2", "c": "3"}{ "a":"1", "b":"2", "c": "3"}{ "a":"1", "b":"2", "c": "3"}' # test string
tmp = tmp.replace('}{', '},{') # replace '}{' with '},{'
tmp = '[' + tmp + ']' # add brackets around it
json_string = json.loads(tmp) # confirm that it's valid json
print(json_string) # print the json_string

will print

[{'a': '1', 'b': '2', 'c': '3'}, {'a': '1', 'b': '2', 'c': '3'}, {'a': '1', 'b': '2', 'c': '3'}]

Upvotes: 3

memre
memre

Reputation: 11

u can use like this

  [
    { "a":"1", 
      "b":"2", 
      "c": "3"
    },
    { "a":"1", 
      "b":"2", 
      "c": "3"
    },
    { "a":"1", 
      "b":"2", 
      "c": "3"
    }
 ]

Upvotes: -1

arun408
arun408

Reputation: 21

not a best solution but it works follow below steps

  1. if the input is in object format then convert into string json.stringify()
  2. replace "}{" with "},{" and append add open and close brackets at the start and end of the string
  3. now convert string to object.

Upvotes: 0

j4nw
j4nw

Reputation: 2405

KISS: replace }{ with },{ and wrap in []

Upvotes: 3

Related Questions