简体   繁体   English

如何在Python中使用JSON从文件的特定列表中检索特定字符串

[英]How to retrieve a specific string from a specific list from a file with JSON in Python

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). 例如,假设仅 user.name为John Connor时才想检索第一个字符串,第二个字符串和第三个字符串(我是说,找到名称的列表中的所有三个值)。 I can't seem to find a proper way to do it googling. 我似乎找不到合适的方法来进行谷歌搜索。 The expected code would be something like this: 预期的代码如下所示:

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. 这就是为什么我只是编写该代码来解释这种情况。

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

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

I suggest that you use the general solution to the problem of extracting data from JSON objects, namely jsonpath. 我建议您使用一般解决方案来解决从JSON对象(即jsonpath)提取数据的问题。 PyPi has this library https://pypi.python.org/pypi/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]'

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

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