简体   繁体   English

从 json 字符串中读取数据并使用 python 对其进行操作

[英]Read data from a json string and manipulate it with python

i have a .json file like this我有一个这样的 .json 文件

{"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.我想在 python 中读取文件,以便我可以获取每个值,以便稍后在我的代码中操作它。 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:但除非我像这样更改 .json 文件,否则它将无法工作:

[
{"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 ?如何在不更改 .json 文件的情况下执行此操作,或者如何使用正则表达式操作该文件,以便我可以运行上述代码来获取每个值?

Thank you very much for your time !非常感谢您的宝贵时间 !

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"])

As comments have already pointed out, your file isn't valid json.正如评论已经指出的那样,您的文件不是有效的 json。 Each line is its own json object and has to be parsed separately.每行都是它自己的 json 对象,必须单独解析。

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.上面的代码使用列表解析来执行以下操作:对于文件中的每一行,将行内容作为字符串读取并使用 json.loads() 方法解析该字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM