【问题标题】:How do you load python lists into JSON Arrays?如何将 python 列表加载到 JSON 数组中?
【发布时间】:2022-12-09 07:25:15
【问题描述】:

我有一些数据

types = ['type1', 'type2', 'type3']
names = ['name1', 'name2', 'name3']

我想将它作为嵌套字符串集加载到 JSON 中,看起来像这样

{
    labels{
        type1:name1
        type2:name2
    }
}

我尝试了一些事情,包括

labels={types:names}                           (didnt work)
labels=json.loads{types:names}                 (various versions of this) 
labels=json.dumps{types:names}                 (various versions of this)
labels=json.loads(json.dumps(types:names))     (I was getting desperate here)

问了一个朋友,他说在python的jsonlib中只能对键值使用变量,不能对键名使用变量。有没有比遍历所有类型和名称更好的方法呢?

【问题讨论】:

    标签: python arrays json list


    【解决方案1】:
    1. 使用 json.dumps() 函数将列表转换为 JSON 字符串。
    2. 然后使用 json.loads() 函数将字符串转换回列表。

    【讨论】:

      【解决方案2】:

      要使用类型和名称列表中的键和值创建 JSON 对象,您可以使用字典理解。这是一种方法:

      import json
      
      types = ['type1', 'type2', 'type3']
      names = ['name1', 'name2', 'name3']
      
      labels = {t: n for t, n in zip(types, names)}
      
      # Print the labels as a JSON string
      print(json.dumps(labels))
      

      zip() 函数用于将类型和名称列表的元素组合成对。然后字典理解创建一个字典,其中类型的元素是键,名称的元素是值。

      可以使用 json.dumps() 函数将生成的字典转换为 JSON 对象。

      或者,您可以创建一个具有类似字典理解的字典列表:

      import json
      
      types = ['type1', 'type2', 'type3']
      names = ['name1', 'name2', 'name3']
      
      labels = [{'type': t, 'name': n} for t, n in zip(types, names)]
      
      # Print the labels as a JSON string
      print(json.dumps(labels))
      

      这会生成一个对象的 JSON 数组,其中每个对象都有键“type”和“name”:

      [  {    "type": "type1",    "name": "name1"  },  {    "type": "type2",    "name": "name2"  },  {    "type": "type3",    "name": "name3"  }]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-25
        • 2015-06-22
        • 2021-07-31
        相关资源
        最近更新 更多