以下是一个示例代码,展示了如何按照内部属性对JSON数组进行过滤:
import json
def filter_json_array(json_array, attribute, value):
filtered_array = []
for item in json_array:
if attribute in item and item[attribute] == value:
filtered_array.append(item)
return filtered_array
# 示例JSON数组
json_data = '''
[
{
"name": "John",
"age": 25,
"city": "New York"
},
{
"name": "Amy",
"age": 30,
"city": "San Francisco"
},
{
"name": "Mike",
"age": 35,
"city": "Los Angeles"
}
]
'''
# 将JSON数据解析为Python对象
json_array = json.loads(json_data)
# 按照内部属性过滤JSON数组
filtered_array = filter_json_array(json_array, "city", "New York")
# 输出过滤后的结果
print(filtered_array)
在上述代码中,filter_json_array
函数接受一个JSON数组、要过滤的属性名和属性值作为参数。它遍历数组中的每个对象,检查该对象是否具有指定的属性,并且属性值等于给定的值。如果是,则将该对象添加到过滤后的数组中。最后,返回过滤后的数组。
在示例中,我们将JSON数据解析为Python对象,并将其传递给filter_json_array
函数进行过滤。我们使用了属性名为"city",值为"New York"进行过滤。最后,打印过滤后的结果。