Python 删除字典中具有整数值的值的引号
我有一个json字典,我想删除json数据中整数值的引号Python 删除字典中具有整数值的值的引号,python,regex,python-3.x,Python,Regex,Python 3.x,我有一个json字典,我想删除json数据中整数值的引号 [ { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": "8.0" }, { "category": "fiction", "autho
[
{
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": "8.0"
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": "90"
}
]
}
]
当我将上述对象传递给函数(即
上面是我想要实现的json数据,如下所示
[
{
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 90
}
]
}
]
首先,如果整型值表示为字符串,那么这是一个非常奇怪的JSON对象 但您可以执行以下操作:
def remove_quote_用于_int_值(对象,字段):
如果存在(对象,列表):
return[删除对象中el的int值(el,字段)]
elif isinstance(obj,dict):
结果={}
对于键,obj.items()中的值:
如果isinstance(值,dict)或isinstance(值,列表):
结果[键]=删除\u int\u值(值、字段)的\u quote\u
elif键输入字段:
结果[键]=int(值)#或所需类型(例如浮点)
其他:
结果[键]=值
返回结果
其他:
返回obj
def-remove-quote-for-int-value(obj):
如果存在(对象,列表):
返回[删除对象中el的内部值(el)的引用]
elif isinstance(obj,dict):
结果={}
对于键,obj.items()中的值:
如果isinstance(值,dict)或isinstance(值,列表):
结果[键]=删除\u int\u值(值)的\u quote\u
其他:
尝试:
值=浮动(值)#或任何所需类型
ValueError除外:#转换为'int'时出现TypeError`
通过
结果[键]=值
返回结果
其他:
返回obj
这两种解决方案也应该适用于嵌套对象。这并不漂亮,可能有一种更简单、更有效的方法可以做到这一点,但这是可行的:
def remove_quote_for_int_values(obj):
for book in obj:
for book_info in book.values():
for elem in book_info:
for key, value in elem.items():
if value.isdigit():
elem[k] = int(value)
输出:
[{'book': [{'category': 'reference', 'author': 'Nigel Rees', 'title': 'Sayings of the Century', 'price': 8}, {'category': 'fiction', 'author': 'Evelyn Waugh', 'title': 'Sword of Honour', 'price': 90}]}]
我不知道是哪一个字段,所以你的2点答案是在论点中询问字段。Shello,我修正了解决方案。第二个现在可以用了。
[{'book': [{'category': 'reference', 'author': 'Nigel Rees', 'title': 'Sayings of the Century', 'price': 8}, {'category': 'fiction', 'author': 'Evelyn Waugh', 'title': 'Sword of Honour', 'price': 90}]}]