search for data in a python json

Asked

Viewed 578 times

0

I have the following code

    with open('states.json') as f:
    data = json.load(f)

for state in data["jquery"]:
    if(argumentos[2] == state['version']):
        print(state['name'], state['version'] + "existe")
    else:
        print("nao tem")

when running the python script

python programa.py jquery 3.3.1

it should search in json where this written jquery and check if it has the second parameter which is version 3.3.1

only that in my code above it goes through the whole json giving me the following exit

jquery 3.3.1 existe
nao tem

he’s validating the 2 lines, if you find it should show success message otherwise it should show message that there is not only that it shows me the 2 messages because in json the first block is true and the second is false in the final output I just want you to show me if there is what I am looking for or nay.

my json

{
"jquery":[
    {
        "name": "jquery",
        "version": "3.3.1",
        "extension": "js",
        "caminho": "https://code.jquery.com/jquery-3.3.1.min.js"
    },
    {
        "name": "jquery",
        "version": "1.5.6",
        "extension": "js",
        "caminho": "https://code.jquery.com/jquery-1.5.6.min.js"
    }
],

"bootstrap":[
    {
        "name": "bootstrap",
        "version": "1.2.8",
        "caminho": "https://bootstrap.com.br"
    }
]
}

If anyone can help me I’d appreciate

  • Tip: Set a variable to False, check and if you find the value set to True, then you display the result based on the variable value, you can even exit the loop if you find the value

  • I tried to do it the way you told me but I’m probably doing it wrong and I can’t get the result I want if you can give me a simple example

1 answer

2


I did it in a very similar way to yours, the only difference is the definition of a variable for the control

It is defined as False, if found will be set to True, then in the end just do the check, if you do not find the content searched, the variable remains with the default value

with open('states.json') as f:
    data = json.load(f)

contem = False

for state in data["jquery"]:
    if (argumento[2] == state['version']):
        contem = True

if (contem):
    print(state['name'], state['version'] + "existe")
else:
    print("nao tem")
  • 1

    thank you very much worked out

  • I came back here I found a problem and I don’t know what it is it ta always returning me the same example value if I run script like this > python program.py jquery 3.3.1 it ta me returning so in console > jquery 1.5.6 exists. in other words, he’s not showing me what I want, but the last json result has some idea of what?

  • Thanks for the tip I managed to solve the problem in the result

Browser other questions tagged

You are not signed in. Login or sign up in order to post.