Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing json data in python

Tags:

python

json

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

like image 229
Firstname Avatar asked Dec 06 '25 09:12

Firstname


1 Answers

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'}
like image 111
Christian Dean Avatar answered Dec 07 '25 23:12

Christian Dean



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!