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

Question:

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("$*%#!@")
Asked By: Leroy Jenkins

||

Answers:

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)
Answered By: tehCheat

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
Answered By: zvz
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.