Home > Software engineering >  How to find information in json file what i need and print those file names?
How to find information in json file what i need and print those file names?

Time:11-26

I have a silly question. So basically, there is allot of JSON files and, for example, i need find to only the JSON files that contains only that information i need now and print those file names that contains that information what i need?

So there's an example: i have an directory where the files are at and this is the information what JSON files contain

{
    "version": "1.0.4",
    "room": {
        "index": 2,
        "label": "Bedroom",
        "score": 0.999368429,
        "threshold": 0.6,
        "raw": {
            "Balcony": {
                "index": 0,
                "score": 0.000324130058
            },
            "Bathroom": {
                "index": 1,
                "score": 8.77380371e-05
            },
            "Bedroom": {
                "index": 2,
                "score": 0.999368429
            },
            "Dining Room": {
                "index": 3,
                "score": 0.000696450472
            },
            "Garage": {
                "index": 4,
                "score": 0.000141739845
            },
            "Hallway": {
                "index": 5,
                "score": 3.37660313e-05
            },
            "Kitchen": {
                "index": 6,
                "score": 4.11570072e-05
            },
            "Laundry Room": {
                "index": 7,
                "score": 9.4473362e-06
            }
,...       
        }
    }
}

Now i need to find all JSON files that contain "label": "Bedroom" and print those file names. Its just for me. I'm learning. Thanks in advance.

CodePudding user response:

Try this

import glob
import json

file_dir = 'wkdir1/' #file location
files = glob.glob(file_dir '*.json')
key = 'Bedroom'
files_with_key = []
for fl in files:
    f = open(fl)
    json_data = json.load(f)
    if key == json_data['room']['label']:
        files_with_key.append(fl)

print(files_with_key)

CodePudding user response:

You can loop through the files in the current directory and check if it contains the information you need.

import os

# The directory that you want to search in. Let's assume that it is named "data"
DIR = "data"
data = "" # The data to check against. I'm not going to write that here, as it is too long.

for file in os.listdir(DIR):
    with open(file, "r") as f:
        if f.readlines() == data:
            print(file)
            break

  • Related