简体   繁体   中英

Storing json data in python

Is there a way to easily store json data in a variable in python. I don't mean the entire json in a variable, rather parsing and storing it as a key-value.

For instance - if this is the json file

[
   [
      1,
      "Apple"
   ],
   [
      2,
      "Orange"
   ],
   [
      3,
      "Grapes"
   ],
   [
      4,
      "Banana"
   ],
   [
      5,
      "Mango"
   ]
]

I want to have a list or some other datatype in python through which I can easily access the data.

Something like variable[1] should print Apple and so on

Yes. You can use the json module. Specifically json.loads . However, if you also want a key value association between your data, you'll need to use a dictionary:

from json import loads

json_data = \
"""
[
    [1, "Apple"],
    [2, "Orange"],
    [3, "Grapes"],
    [4, "Banana"],
    [5, "Mango"]
]
"""

data = dict(loads(json_data))
print(data)
# {1: u'Apple', 2: u'Orange', 3: u'Grapes', 4: u'Banana', 5: u'Mango'}

Unsurprisingly, you need the json module.

In [29]: import json

In [30]: data = '''[
    ...:    [
    ...:       1,
    ...:       "Apple"
    ...:    ],
    ...:    [
    ...:       2,
    ...:       "Orange"
    ...:    ],
    ...:    [
    ...:       3,
    ...:       "Grapes"
    ...:    ],
    ...:    [
    ...:       4,
    ...:       "Banana"
    ...:    ],
    ...:    [
    ...:       5,
    ...:       "Mango"
    ...:    ]
    ...: ]'''

In [31]: json.loads(data)
Out[31]: [[1, 'Apple'], [2, 'Orange'], [3, 'Grapes'], [4, 'Banana'], [5, 'Mango']]

The module also contains functions to handle data in files.

To extract the fruit names by numerical key could be done in several ways, but they all involve transforming the data further. For example:

In [32]: fruits = []

In [33]: for key, name in json.loads(data):
    ...:     fruits.append(name)
    ...:

In [34]: fruits[0]
Out[34]: 'Apple'

Here Python's zero-based indexing slightly defeats the value of this solution given that the keys start with 1. A dictionary gives you exactly what you need. If you call the dict constructor with a list of pairs it will treat them as key, value pairs.

In [35]: fruits = dict(json.loads(data))

In [36]: fruits[1]
Out[36]: 'Apple'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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