2

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

2 Answers 2

6

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'}
Sign up to request clarification or add additional context in comments.

Comments

3

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.