简体   繁体   English

在 json 文件中搜索字符串并提取其部分

[英]Searching for a string in a json file and extracting its section

I was wondering how to perform the following: 1.search for strings in a json and extract their nested components.我想知道如何执行以下操作: 1.在 json 中搜索字符串并提取它们的嵌套组件。 given:给定:

"type": "blah",
"animals": [
    {
        "type": "dog1",
        "name": "oscar",
        }
    },
    {
        "type": "dog2",
        "name": "John",
        }
    },
    {
        "type": "cat1",
        "name": "Fred",
        "Colors": [
            "Red"
        ],
        "Contact_info": [
            {
                "Owner": "Jill",
                "Owner_number": "123"
            }
        ],
    
    },
    {
        "type": "cat3",
        "name": "Freddy",
        "Colors": [
            "Blue"
        ],
        "Contact_info": [
            {
                "Owner": "Ann",
                "Owner_number": "1323"
            }
        ],

From this json, I would like to extract all of the animals that are of type cat like cat1 and cat2, as well as all of the information within that block.从这个 json 中,我想提取所有 cat 类型的动物,如 cat1 和 cat2,以及该块中的所有信息。 Like if I search for cat it should return:就像我搜索 cat 它应该返回:

{
    "type": "cat1",
    "name": "Fred",
    "Colors": [
        "Red"
    ],
    "Contact_info": [
        {
            "Owner": "Jill",
            "Owner_number": "123"
        }
    ],

},
{
    "type": "cat3",
    "name": "Freddy",
    "Colors": [
        "Blue"
    ],
    "Contact_info": [
        {
            "Owner": "Ann",
            "Owner_number": "1323"
        }
    ],

Not necessarily that format, but just all of the information that has type cat.不一定是那种格式,只是所有类型为 cat 的信息。 Im trying to search for objects in a json file and extract features from that search as well as anything nested inside of it.我试图在 json 文件中搜索对象并从该搜索中提取特征以及嵌套在其中的任何内容。 Here is my code so far:到目前为止,这是我的代码:



f = open('data.json')
 
# returns JSON object as
# a dictionary
data = json.load(f)
 
# Iterating through the json
# list
for i in data:
    if i['type'] == 'cat':
        print(i['name'])
        print(i['colors'])

        break
 
# Closing file
f.close()```

To begin with, I recommend using the with statement that creates a runtime context that allows you to run a group of statements under the control of a context manager.首先,我建议使用with语句创建运行时上下文,允许您在上下文管理器的控制下运行一组语句。

It's much more readable and allows you to skip closing the file since the context manager will do everything for you.它更具可读性,并且允许您跳过关闭文件,因为上下文管理器将为您做所有事情。

Moving to your problem转移到你的问题

Suppose your file is called animals.json假设您的文件名为animals.json

# Import json library to work with json files
import json

# Use context manager
with open("animals.json", "rb") as f:
    # Load animals list from json file
    animals = json.load(f)["animals"]

# Create a list of dictionaries if animal type contains "cat"
cats = [animal for animal in animals if "cat" in animal.get("type")]

# Write data to cats.json
json.dump(cats, open("cats.json", "w"), indent=4, sort_keys=False, ensure_ascii=False)

This code outputs the formatted cats.json file with all necessary elements:此代码输出带有所有必要元素的格式化cats.json文件:

[
    {
        "type": "cat1",
        "name": "Fred",
        "Colors": [
            "Red"
        ],
        "Contact_info": [
            {
                "Owner": "Jill",
                "Owner_number": "123"
            }
        ]
    },
    {
        "type": "cat3",
        "name": "Freddy",
        "Colors": [
            "Blue"
        ],
        "Contact_info": [
            {
                "Owner": "Ann",
                "Owner_number": "1323"
            }
        ]
    }
]

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

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