Home > Software design >  Converting objects in file to json in python
Converting objects in file to json in python

Time:06-07

I have a file with multiple objects like this:

{ 
    name: (sindey, crosby)
    game: "Hockey"
    type: athlete
},
{ 
    name: (wayne, gretzky)
    game: "Ice Hockey"
    type: athlete
}

...and I'd like to convert them to JSON format and output this:

[
    { 
        "name": "(sindey, crosby)",
        "game": "Hockey",
        "type": "athlete"
    },
    { 
        "name": "(wayne, gretzky)",
        "game": "Ice Hockey",
        "type": "athlete"
    }
]

If the input was in this format,

 name: (sidney, crosby) | game:"Hockey" |  type:athlete 
 name: (wayne, gretzky) | game:"Ice Hockey" |  type:athlete

I could implement using json dump with list and dict and it gives me the desired output

import json

f = open("log.file", "r")
content = f.read()
splitcontent = content.splitlines()

d = []
for v in splitcontent:
    l = v.split(' | ')
    d.append(dict(s.split(':',1) for s in l))


with open("json_log.json", 'w') as file:
    file.write((json.dumps(d, indent=4, sort_keys= False)))

How can I reformat this code to convert my input to JSON format?

CodePudding user response:

With slight changes on the answer given by @sarah Messer. Changes involved

lines without the : separator skipped

Try this

import json


f = open("log.file", "r")
content = f.read()
splitcontent = content.splitlines()

d = []
appendage = {}
for line in splitcontent:

    if ('}' in line) or ('{' in line) or ('{' in line) or ('}' in line):
        # Append a just-created record and start a new one
        if appendage:
            d.append(appendage)
            appendage = {}
        continue

    key, val = line.split(':')

    if val.endswith(','):
        # strip a trailing comma
        val = val[:-1]
        print(val)
    # if val == "":
    #     pass
    # else:
    appendage[key] = val


with open("json_log.json", 'w') as file:
    file.write((json.dumps(d, indent=4, sort_keys=False)))

CodePudding user response:

Something like this will probably work for most cases - you just have to handle the lines with curly braces separately from the lines with data:

import json

f = open("log.file", "r")
content = f.read()
splitcontent = content.splitlines()

d = []
appendage = {}
for line in splitcontent:
    if ('}' in line) or ('{' in line):
        # Append a just-created record and start a new one
        if appendage:
            d.append(appendage)
        appendage ={}
    else:
        key, val = line.split(':',1)
        if val.endswith(','):
            # strip a trailing comma
            val = val[:-1]
        appendage[key] = val


with open("json_log.json", 'w') as file:
    file.write((json.dumps(d, indent=4, sort_keys= False)))

I might also have some typos in there...

  • Related