Skip to content Skip to sidebar Skip to footer

How To Create This Type Of Json

I have a tuple like mytuple = ('somevalue', 99999, 'jjj', 99) from this tuple I want to make json like { 'key1':'somevalue', 'key2':'99999, 'key3':'jjj', 'key4':99 } the number

Solution 1:

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) }

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}'

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.


Post a Comment for "How To Create This Type Of Json"