Jonathan Dacian
Jonathan Dacian

Reputation: 3

How to save JSON key data to Python Variables

is there a way to store my JSON key data(id,name,price...) on each of my variable(id1-id3, id1-id3, price1-price3...)

here is my sample code

import json

from kivy.properties import StringProperty

f = open('sample.json')
data = json.load(f)

id1 = StringProperty(None)
id2 = StringProperty(None)
id3 = StringProperty(None)

name1 = StringProperty(None)
name2 = StringProperty(None)
name3 = StringProperty(None)

price1 = StringProperty(None)
price2 = StringProperty(None)
price3 = StringProperty(None)

quantity1  = StringProperty(None)
quantity2  = StringProperty(None)
quantity3  = StringProperty(None)

for i in data:
    print(i)

and here is the JSON file

[
  {
    "id": "p01",
    "name": "Name 1",
    "price": 1,
    "quantity": 1
  },
  {
    "id": "p02",
    "name": "Name 2",
    "price": 2,
    "quantity": 2
  },
  {
    "id": "p03",
    "name": "Name 3",
    "price": 3,
    "quantity": 3
  }
]

i'm planning to use bigger data. but for simplicity's sake, i just use 3 items as an example

Upvotes: 0

Views: 4314

Answers (2)

Rani Rajput
Rani Rajput

Reputation: 41

You can simply use json module with python dictionary as follow:

# Import the module
import json

# String with JSON format
data_JSON =  """
[
  {
    "id": "p01",
    "name": "Name 1",
    "price": 1,
    "quantity": 1
  },
  {
    "id": "p02",
    "name": "Name 2",
    "price": 2,
    "quantity": 2
  },
  {
    "id": "p03",
    "name": "Name 3",
    "price": 3,
    "quantity": 3
  }
]
"""

# Convert JSON string to dictionary
data_dict = json.loads(data_JSON)
print(data_dict)

Upvotes: 0

Muhammad Yousuf Noor
Muhammad Yousuf Noor

Reputation: 197

You don't need to store each value of JSON in a new variable, you can use a python dictionary.

See JSON and Python Dictionary

import json

#opening json file
with open("data.json") as f:
    #converting json to python dict and stroing it in data variable
    data = json.loads(f.read())

#iterating dict items and printing values
for items in data:
    print(items['id'],items['name'],items['price'])

#you can also access dict values like this
#0 is the index number.
print(data[0]['id'])
print(data[0]['name'])
print(data[0]['price'])

#similarly
print(data[1]['id'])
print(data[2]['id'])

Upvotes: 1

Related Questions