删除字典中具有整数值的值的引号

2024-04-20 07:24:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个json字典,我想删除整个json数据中整数值的引号。你知道吗

[
  {
    "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"
      }
    ]
  }
]

当我将上述对象传递给一个函数(即

def remove_quote_for_int_values(obj):
    print(expected_output_is_below)
    pass

上面是我想要实现的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
      }
    ]
  }
]

Tags: ofthe数据jsontitlepriceauthorreference
2条回答

首先,如果整数值表示为字符串,那么这是一个非常奇怪的JSON对象。你知道吗

但您可以执行以下操作:

  1. 如果您知道哪些字段是整数:
def remove_quote_for_int_values(obj, fields):
    if isinstance(obj, list):
        return [remove_quote_for_int_values(el, fields) for el in obj]
    elif isinstance(obj, dict):
        result = {}
        for key, value in obj.items():
            if isinstance(value, dict) or isinstance(value, list):
                result[key] = remove_quote_for_int_values(value, fields)
            elif key in fields:
                result[key] = int(value)  # or the desired type (e.g. float)
            else:
                result[key] = value
        return result
    else:
        return obj
  1. 如果你不知道
def remove_quote_for_int_values(obj):
    if isinstance(obj, list):
        return [remove_quote_for_int_values(el) for el in obj]
    elif isinstance(obj, dict):
        result = {}
        for key, value in obj.items():
            if isinstance(value, dict) or isinstance(value, list):
                result[key] = remove_quote_for_int_values(value)
            else:
                try:
                    value = float(value)  # or any desired type
                except ValueError:  # TypeError when converting to `int`
                    pass
                result[key] = value
        return result
    else:
        return 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}]}]

相关问题 更多 >