简体   繁体   English

PYTHON 将字符串列表转换为 JSON 具有键和值的对象数组

[英]PYTHON convert list of strings to JSON array of objects with key and value

I'm using PYTHON :我正在使用PYTHON

I'm trying to convert the following array of strings:我正在尝试转换以下字符串数组:

tags_list = ["one", "two", "three"]

to an array of JSON array of objects with a specific key as follows:到具有特定键的 JSON 对象数组,如下所示:

    "tags": [
        {
            "name": "one"
        },
        {
            "name": "two"
        },
        {
            "name": "three"
        }
    ]

I found several answers for JavaScript not python我找到了 JavaScript 而非 python 的几个答案

Can any body help please任何人都可以帮忙吗

Thanks in-advance提前致谢

Almost the same as @sudden_appearance mentioned, but I'd add:几乎与提到的@sudden_appearance 相同,但我要补充:

print(json.dumps(json_dict, indent=2)) 

when you log it to the console, for a better format:)当您将其记录到控制台时,为了更好的格式:)

try this is full example of your code尝试这是您的代码的完整示例

import json
tags_list = ["one", "two", "three"]

#prepare array to object
json_dict = {"tags": [{"name": value} for value in tags_list]}

#object to json String
json_string= json.dumps(json_dict)
print(json_string) #for print json if needed

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM