英文:
How to remove properties from jason object using Python
问题
我有一个类似下面的Json对象(字典):
{
name = 'John',
address = '123 bb',
age = '40',
children:[
{
name ="smith',
address ='458 ff',
age = '25',
grand_children: [
{
name ="smith',
address ='458 ff',
age = '25'
},
{
name ="smith',
address ='458 ff',
age = '25'
}
]
},
{
name ="smith',
address ='458 ff',
age = '25',
grand_children: [
{
name ="smith',
address ='458 ff',
age = '25'
},
{
name ="smith',
address ='458 ff',
age = '25'
}
]
}
]
}
有没有一种简单的方法逐个删除属性,例如逐个删除名称(name)?
英文:
I have a Json Object (Dict) like below:
{name = 'John',
address = '123 bb',
age = '40'
children:[{ name ="smith',
address ='458 ff',
age = '25',
grand_children [{name ="smith',
address ='458 ff',
age = '25'},
{name ="smith',
address ='458 ff',
age = '25'}],
{ name ="smith',
address ='458 ff',
age = '25',
grand_children [{name ="smith',
address ='458 ff',
age = '25'},
{name ="smith',
address ='458 ff',
age = '25'}]]}
is there a easy way of remove property one at a time
e.g remove names (one at a time)?
答案1
得分: 0
这是用于从对象中移除属性的代码(递归地从其子对象中也移除)。
def remove_property(obj, prop_name):
if isinstance(obj, dict):
if prop_name in obj:
del obj[prop_name]
for value in obj.values():
remove_property(value, prop_name)
elif isinstance(obj, list):
for item in obj:
remove_property(item, prop_name)
示例用法
data = {
'name': 'John',
'address': '123 bb',
'age': '40',
'children': [
{
'name': 'smith',
'address': '458 ff',
'age': '25',
'grand_children': [
{
'name': 'smith',
'address': '458 ff',
'age': '25'
},
{
'name': 'smith',
'address': '458 ff',
'age': '25'
}
]
},
{
'name': 'smith',
'address': '458 ff',
'age': '25',
'grand_children': [
{
'name': 'smith',
'address': '458 ff',
'age': '25'
},
{
'name': 'smith',
'address': '458 ff',
'age': '25'
}
]
}
]
}
remove_property(data, 'name')
print(data)
或者
如果您只想删除一个属性(不递归),可以使用 `del` 关键字。
<details>
<summary>英文:</summary>
This is code for removing a property from the object (recursively from its children too.)
```python
def remove_property(obj, prop_name):
if isinstance(obj, dict):
if prop_name in obj:
del obj[prop_name]
for value in obj.values():
remove_property(value, prop_name)
elif isinstance(obj, list):
for item in obj:
remove_property(item, prop_name)
# Example usage
data = {
'name': 'John',
'address': '123 bb',
'age': '40',
'children': [
{
'name': 'smith',
'address': '458 ff',
'age': '25',
'grand_children': [
{
'name': 'smith',
'address': '458 ff',
'age': '25'
},
{
'name': 'smith',
'address': '458 ff',
'age': '25'
}
]
},
{
'name': 'smith',
'address': '458 ff',
'age': '25',
'grand_children': [
{
'name': 'smith',
'address': '458 ff',
'age': '25'
},
{
'name': 'smith',
'address': '458 ff',
'age': '25'
}
]
}
]
}
remove_property(data, 'name')
print(data)
OR
if you just want to delete a property (not recursively) use the del
keyword.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论