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'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With