[英]Searching for a string in a json file and extracting its section
我想知道如何執行以下操作: 1.在 json 中搜索字符串並提取它們的嵌套組件。 給定:
"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"
}
],
從這個 json 中,我想提取所有 cat 類型的動物,如 cat1 和 cat2,以及該塊中的所有信息。 就像我搜索 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"
}
],
不一定是那種格式,只是所有類型為 cat 的信息。 我試圖在 json 文件中搜索對象並從該搜索中提取特征以及嵌套在其中的任何內容。 到目前為止,這是我的代碼:
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()```
with
語句創建運行時上下文,允許您在上下文管理器的控制下運行一組語句。它更具可讀性,並且允許您跳過關閉文件,因為上下文管理器將為您做所有事情。
假設您的文件名為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)
此代碼輸出帶有所有必要元素的格式化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.