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

时间:2019-05-02 09:52:00

标签: python regex python-3.x

我有一个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
      }
    ]
  }
]

2 个答案:

答案 0 :(得分:1)

首先,如果整数值在那里表示为字符串,那将是一个非常奇怪的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

这两个解决方案也应适用于嵌套对象。

答案 1 :(得分:0)

这不是很漂亮,并且可能有一种更简单,更有效的方法来做到这一点,但这可行:

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}]}]