1

i have a .json file like this

{"name":"george" , "age":28 , "gender":"male"}
{"name":"maria" , "age":20 , "gender":"female"}
{"name":"mike" , "age":22 , "gender":"male"}

and i want to read the file in python so i can get each value so i can manipulate it later in my code. I have tried the code below:

with open ("file.json" , "r") as f:
data = json.load(f)
for line in data:
    print (line["name"])

but it won't work unless i change .json file like this:

[
{"name":"george" , "age":28 , "gender":"male"},
{"name":"maria" , "age":20 , "gender":"female"},
{"name":"mike" , "age":22 , "gender":"male"}
]

how can i do it without changing the .json file or how i can manipulate the file with regex so i can run the above code to take each value ?

Thank you very much for your time !

1
  • 2
    The file you have isn't valid JSON, you need to do whatever it takes to convert the file into valid JSON before you can parse it as JSON. You need commas, and you need brackets for a JSON array with multiple items. I wouldn't use a regex to preprocess the JSON and fix it unless you have a ton of files like this or you have no control over the format of the files. Commented Jan 10, 2020 at 20:06

2 Answers 2

2

Assuming each dictionary is stored in a new line, You can use:

import json
with open ("file.json" , "r") as f:
    data = [json.loads(val) for val in f.readlines()]
for line in data:
    print (line["name"])

Additionaly if the dictionaries are not stored in different lines, you can use:

import json
with open ("file.json" , "r") as f:
    data = []
    opn = 0
    cur = ''
    for char in a.strip():
    if char == '{':
         opn += 1
    elif char == '}':
        opn -= 1
    cur += char
    if opn == 0:
        data.append(json.loads(cur))
        cur = ''
for line in data:
    print (line["name"])
Sign up to request clarification or add additional context in comments.

3 Comments

I didn't think about accounting for the second case. Great answer.
{"foo": {"bar": 1},} wouldn't be valid json (not sure if it would be an issue for this case)
@Sayse Oh Yea you're right, I was considering in terms of dictionaries. Ill update my answer
0

As comments have already pointed out, your file isn't valid json. Each line is its own json object and has to be parsed separately.

with open ("file.json" , "r") as f:
    data = [json.loads(line) for line in f.readlines()]

The code above uses a list comprehension to do the following: for each line in your file, read the line contents as a string and parse the string with the json.loads() method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.