如何删除Json键中的空格?

时间:2018-01-19 23:26:50

标签: python json key spaces

示例:

输入:

{"Contact Title": "Owner Name"}

预期产出:

{"ContactTitle": "Owner Name"}

2 个答案:

答案 0 :(得分:0)

使用json object_hooks(支持嵌套字典)的示例:

In [1]: import json
   ...: 
   ...: example_dict = {'ke  y1': 'value1',
   ...:  'ke y2': 'value2',
   ...:  'k ey3': {'key3a': 'value3a'},
   ...:  'key 4': {'key 4a': {'key4a   a': {'key 4 4 4 44': 'value44 4   44'},
   ...:    'key4 ab': 'value  4ab',
   ...:    'key4ac': 'va lue4ac'},
   ...:   'k ey4b': 'valu  e4b'}}
   ...: 
   ...: def remove_spaces(obj):
   ...:     for key in obj.keys():
   ...:         new_key = key.replace(" ","")
   ...:         if new_key != key:
   ...:             obj[new_key] = obj[key]
   ...:             del obj[key]
   ...:     return obj
   ...: 
   ...: new_json = json.loads(json.dumps(example_dict), object_hook=remove_spaces) 
   ...: 
   ...: new_json
   ...: 
Out[1]: 
{u'key1': u'value1',
 u'key2': u'value2',
 u'key3': {u'key3a': u'value3a'},
 u'key4': {u'key4a': {u'key4aa': {u'key44444': u'value44 4   44'},
   u'key4ab': u'value  4ab',
   u'key4ac': u'va lue4ac'},
  u'key4b': u'valu  e4b'}}

还有另一种方法(只要你不超过递归深度就更好):

In [2]: def dict_key_unspacer(d):
    ...:     new = {}
    ...:     for k, v in d.iteritems():
    ...:         if isinstance(v, dict):
    ...:             v = print_dict(v)
    ...:         new[k.replace(' ', '')] = v
    ...:     return new
    ...: 
    ...: result_dict = dict_key_unspacer(example_dict)
    ...: 
    ...: result_dict
    ...: 
Out[2]: 
{'key1': 'value1',
 'key2': 'value2',
 'key3': {'key3a': 'value3a'},
 'key4': {'key4a': {'key4aa': {'key44444': 'value44 4   44'},
   'key4ab': 'value  4ab',
   'key4ac': 'va lue4ac'},
  'key4b': 'valu  e4b'}}

答案 1 :(得分:0)

谢谢你的建议,我在一行中尝试了一些正则表达式并且工作正常,但我看到输出中的顺序发生了变化。

input = [{     “Id”:“ALFKI”,     “联系人姓名”:“Maria Anders”,     “联系人标题”:“销售代表”,     “城市”:“柏林”,     “滑块”:10 },{     “Id”:“ANATR”,     “联系人姓名”:“Ana Trujillo”,     “联系人标题”:“所有者”,     “城市”:“墨西哥D.F.”,     “滑块”:5 }]

new_json =(re.sub(r'\ s(?= \ w +“:)',”“,str(json.dumps(input))))

输出= [   {     “ContactName”:“Maria Anders”,     “ContactTitle”:“销售代表”,     “Id”:“ALFKI”,     “滑块”:10,     “城市”:“柏林”   },   {     “ContactName”:“Ana Trujillo”,     “ContactTitle”:“所有者”,     “Id”:“ANATR”,     “滑块”:5,     “城市”:“墨西哥D.F.”   } ]