【问题标题】:Convert JSON Dictionary to JSON Array in python在python中将JSON字典转换为JSON数组
【发布时间】:2019-04-19 19:50:16
【问题描述】:

我有类似这样的 JSON 字典:

{'foo': 3, 'bar': 1}

我希望它是 JSON 数组形式:

[ { "key": "foo", "value": 3 }, { "key": "bar", "value": 1 }] 

我该怎么办?

【问题讨论】:

标签: python arrays json


【解决方案1】:

您需要遍历此字典的键和值,然后在新字典中分配必要的键。

import json

input_dict = {'foo': 3, 'bar': 1}
result = []

for k, v in input_dict.items():
    result.append({'key': k, 'value': v})

print(json.dumps(result))

结果:

[{'value': 3, 'key': 'foo'}, {'value': 1, 'key': 'bar'}]

【讨论】:

    【解决方案2】:

    这可以通过list comprehension 处理:

    import json
    json_dict = {'foo': 3, 'bar': 1}
    json_array = [ {'key' : k, 'value' : json_dict[k]} for k in json_dict]
    print(json.dumps(json_array))
    

    输出:

    [{"key": "foo", "value": 3}, {"key": "bar", "value": 1}]

    【讨论】:

      【解决方案3】:

      试试这个(Python 2.7 及更高版本):

      json_dict = {'foo': 3, 'bar': 1}  # your original dictionary;
      json_array = []  # an array to store key-value pairs;
      
      # Loop through the keys and values of the original dictionary:
      for key, value in json_dict.items():
          # Append a new dictionaty separating keys and values from the original dictionary to the array:
          json_array.append({'key': key, 'value': value})
      

      做同样事情的单线:

      json_array = [{'key': key, 'value': value} for key, value in {'foo': 3, 'bar': 1}.items()]
      

      希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 2018-05-04
        • 2021-01-17
        • 1970-01-01
        • 2011-01-29
        • 1970-01-01
        • 2012-07-03
        • 2015-10-16
        相关资源
        最近更新 更多