如何从包含JSON的文件中从特定的列表中检索特定的字符串?

时间:2021-09-12 20:24:50

I got code that actually saves three different data strings in the same list. Each list is separated and I'm not even sure if that made sense... So I'm going to just paste the code:

我得到的代码实际上在同一个列表中保存了三个不同的数据字符串。每个列表都是分开的,我甚至不确定这是否有意义……我将粘贴代码

    filename = "datosdeusuario.txt"
    leyendo = open(filename, 'r+')
    buffer = leyendo.read()
    leyendo.close()
    if not user.name in buffer:
      escribiendo = open(filename, 'a')
      escribiendo.write(json.dumps([user.name, string2, string3])+"\n")
      escribiendo.close()
      print(str(horaactual)[:19] + ": Data from " + user.name + " added")

That code is saving information like this (and working almost perfect):

这段代码保存了这样的信息(并且几乎是完美的):

["saelyth", "thisisanexampleforstring2", "andthisisanexampleforstring3"]
["anothername", "thisisanothernexampleforstring2", "andthisisanotherexampleforstring3"]
["John Connor", "exampleforstring2", "exampleforstring3"]

So my actual question and problem is... What is the best way to get an specific string from that file?

所以我真正的问题是。从该文件获取特定字符串的最佳方式是什么?

For example, let's say I want to retrieve the first string, the second string and the third string only if the user.name is John Connor (I mean, all three values from the list where the name is found). I can't seem to find a proper way to do it googling. The expected code would be something like this:

例如,假设我想要检索第一个字符串,第二个字符串和第三个字符串,只有用户名是John Connor(我是说,从列表中找到的三个值)。我似乎找不到一种合适的方法来搜索它。预期的代码是这样的:

if user.name is in found in any list(position1) of the file datosdeusuario.txt
then
retrieveddata1 = List where value1 is user.name(get value1)
retrieveddata2 = List where value1 is user.name(get value2)
retrieveddata3 = List where value1 is user.name(get value3)

I have no idea how to do that. That's why I just made up that code to explain the situation.

我不知道怎么做。这就是为什么我编写代码来解释这种情况。

3 个解决方案

#1


0  

Maybe this would work:

也许这将工作:

retrieveddata1 = retrieveddata2 = retrieveddata3 = None
filename = "datosdeusuario.txt"
for line in open(filename, 'r'):
    retrieved = json.loads(line)
    if retrieved[0] == 'jonh connor':
        retrieveddata1 = retrieved[0]
        retrieveddata2 = retrieved[1]
        retrieveddata3 = retrieved[2]
        break

#2


1  

I am not sure if this is what you want but:

我不确定这是否是你想要的,但是:

filename = "datosdeusuario.txt"
f = open(filename,"r")
filedata = f.read()
f.close()
sp1 = filedata.split("\n")
a = ""
for x in sp1:
    if "joao m" in x:
        a = x
if(len(a) > 0):
    sp2 = a.split('"')
    values = []
    for x in sp2:
        if not(x == ", " or x == "]" or x == "[" or len(x) == 0):
            values.append(x)
    print values[0] #should by the name
    print values[1] #value 2
    print values[2] #value 3       
else: #No username in the file
    #do something
    pass

#3


0  

I suggest that you use the general solution to the problem of extracting data from JSON objects, namely jsonpath. PyPi has this library https://pypi.python.org/pypi/jsonpath/

我建议您使用通用解决方案来从JSON对象(即jsonpath)中提取数据。PyPi有这个库https://pypi.python.org/pypi/jsonpath/

if jsonpath.jsonpath(jsondata,'$[0]') == 'John Connor':
    result = jsonpath.jsonpath(jsondata,'$[2]')

Yes, the documentation for the Python library sucks but the code is straightforward to read through, and JSONPATH expressions are documented fairly well by other implementors.

是的,Python库的文档很糟糕,但是代码很容易阅读,JSONPATH表达式被其他实现人员很好地记录下来。

Consider making your code clearer by adding something like:

考虑通过添加以下内容使代码更清晰:

NAME = '$[0]'
STUFF = '$[1]'
OTHERSTUFF = '$[2]'

#1


0  

Maybe this would work:

也许这将工作:

retrieveddata1 = retrieveddata2 = retrieveddata3 = None
filename = "datosdeusuario.txt"
for line in open(filename, 'r'):
    retrieved = json.loads(line)
    if retrieved[0] == 'jonh connor':
        retrieveddata1 = retrieved[0]
        retrieveddata2 = retrieved[1]
        retrieveddata3 = retrieved[2]
        break

#2


1  

I am not sure if this is what you want but:

我不确定这是否是你想要的,但是:

filename = "datosdeusuario.txt"
f = open(filename,"r")
filedata = f.read()
f.close()
sp1 = filedata.split("\n")
a = ""
for x in sp1:
    if "joao m" in x:
        a = x
if(len(a) > 0):
    sp2 = a.split('"')
    values = []
    for x in sp2:
        if not(x == ", " or x == "]" or x == "[" or len(x) == 0):
            values.append(x)
    print values[0] #should by the name
    print values[1] #value 2
    print values[2] #value 3       
else: #No username in the file
    #do something
    pass

#3


0  

I suggest that you use the general solution to the problem of extracting data from JSON objects, namely jsonpath. PyPi has this library https://pypi.python.org/pypi/jsonpath/

我建议您使用通用解决方案来从JSON对象(即jsonpath)中提取数据。PyPi有这个库https://pypi.python.org/pypi/jsonpath/

if jsonpath.jsonpath(jsondata,'$[0]') == 'John Connor':
    result = jsonpath.jsonpath(jsondata,'$[2]')

Yes, the documentation for the Python library sucks but the code is straightforward to read through, and JSONPATH expressions are documented fairly well by other implementors.

是的,Python库的文档很糟糕,但是代码很容易阅读,JSONPATH表达式被其他实现人员很好地记录下来。

Consider making your code clearer by adding something like:

考虑通过添加以下内容使代码更清晰:

NAME = '$[0]'
STUFF = '$[1]'
OTHERSTUFF = '$[2]'