Home > Software design >  Output converted JSON value in Python
Output converted JSON value in Python

Time:06-07

I have the code to covert this input into json format in python:

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

Code:

import json
import os

user_input = input("Enter the path of your file: ")
assert os.path.exists(user_input), "Invalid file at, "   str(user_input)
f = open(user_input, 'r')
content = f.read()

def parse_records(txt):
    reclines = []
    for line in txt.split('\n'):
        if ':' not in line:
            if reclines:
                yield reclines
                reclines = []
        else:
            reclines.append(line)

def parse_fields(reclines):
    res = {}
    for line in reclines:
        key, val = line.strip().rstrip(',').split(':', 1)
        res[key.strip()] = val.strip()
    return res

res = []
for rec in parse_records(content):
    res.append(parse_fields(rec))

print(json.dumps(res, indent=4))

Output:

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

I want to output specific json value of name ie:

(sidney, crosby), athlete
(wayne, gretzky), athlete

I added these lines

 res = []
for rec in parse_records(content):
    res.append(parse_fields(rec))

    my_json = json.load(res)
for data in my_json:
    print(data["name"], data["type"])

but I get the error:

Traceback (most recent call last):
  File "C:\Users\670274890\PycharmProjects\Proj\main.py", line 30, in <module>
    my_json = json.load(res)
  File "C:\Users\670274890\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
AttributeError: 'list' object has no attribute 'read'

Would I need to store the converted json file and then parse it to output the specific values or is there a way to fix up the last few lines I wrote to get the desired output?

CodePudding user response:

You don't need json once you have your res list. You just iterate over that list printing what you need:

for person in res:
    print(person["name"], person["type"])

If you need to save res to a file, then json format seems reasonable. You should have this at the end of your program:

with open('output.json', 'w') as file:
    json.dumps(res, file, indent=4)
  • Related