如何创建这种类型的json [英] How to create this type of json

查看:132
本文介绍了如何创建这种类型的json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似

mytuple = ('somevalue', 99999, 'jjj', 99)

从这个元组中我想使json像

from this tuple I want to make json like

{
"key1":'somevalue',
"key2":'99999,
"key3":'jjj',
"key4":99
}

键的数量不是恒定的,它们可以更改,键的值和数量也等于对象的数量

the number of keys are not constant they can change and also value and number of keys are equal to number of objects

我尝试过

data = {}
        for i in range(0,maxLen):
            key = keydata[0][i]
            value = valuedata[0][i]
            data[key] = data[value]

我在创建json时遇到关键错误

I am getting key error while creating json

推荐答案

您可以使用enumerate(..)获取索引.因此,我们可以构建一个像这样的字典:

You can use enumerate(..) to obtain the index. We can thus construct a dictionary like:

{ 'key{}'.format(i): v for i, v in enumerate(mytuple, 1) }

然后我们可以使用json.dumps检索JSON blob:

We can then use json.dumps to retrieve the JSON blob:

>>> json.dumps({ 'key{}'.format(i): v for i, v in enumerate(mytuple, 1) }) 
'{"key1": "somevalue", "key2": 99999, "key3": "jjj", "key4": 99}'

请注意,您提供的JSON不是有效的JSON,因为JSON字符串被双引号(so "…")包围,此外,您的99999前面带有单引号(').例如,您可以使用 jsonlint 之类的服务来对此进行验证.有效的JSON Blob例如:

Note that the JSON you provided is not valid JSON, since a JSON string i surrounded by double quotes (so "…"), and furthermore your 99999 has a single quote (') in front. You can validate this with a service like jsonlint for example. A valid JSON blob is for example:

{
    "key1": "somevalue",
    "key2": 99999,
    "key3": "jjj",
    "key4": 99
}

除了格式化外,它与这里构造的相同,但是,例如,当您获取数据时,仅开销.

This is the same as the one constructed here, except for the formatting, but that is, when you for example fetch data, only overhead.

这篇关于如何创建这种类型的json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆