Home > Mobile >  In python, how do you search for a tag value pair in a JSON file
In python, how do you search for a tag value pair in a JSON file

Time:01-07

Im dealing with a large json file that has many boolean values, so I cant just search on the value alone. How can I extract the entire user information if one value is true?

For example the json file has many lines that could read something like this:

[
    12,
    {
        "name": "Big Bird",
        "muting": false,
        "following": true,
        "blocked_by": false,
        "followers_count": 42
    }
]

How can I iterate through the file to find all users who could be set to muting as true?

The code I have is import json

with open("tempList") as f:
    data = json.load(f)
    for key in data:
        if key['muting'] == "false":
            print("YES")
        else:
            print("$*%#!@")

CodePudding user response:

Since it appears some values for user will be integers, we can explicitly check the type of user to avoid problems; also, using .get to access the dict will avoid KeyError if the key is not present. Thus:

users_with_muting = []
with open("tempList") as f:
    data = json.load(f)
    for user in data:
        if type(user) == dict and user.get("muting") == True:
            users_with_muting.append(user)

CodePudding user response:

For the first question

How can I extract the entire user information if one value is true?

def get_user_with_true(json_file: str):
    users_with_true = []
    with open(json_file, 'r') as f:
        json_str = f.read()
        json_data = json.loads(json_str)
        for u in json_data:
            if True in u.values():
                users_with_true.append(u)
    return users_with_true
  • Related