This is my JSON data
[
{
"id":1,
"name":"abc",
"phone": "12345",
"Charecteristics": [
{
"id":1,
"name":"Good Looking",
"rating": "Average",
}
{
"id":2,
"name":"Smart",
"rating": "Excellent",
}
]
},
{ ... },
{ ... }
]
I have two Classes in Python
class Character(object):
id = 0
name = ""
rating = ""
class Person(object):
id = 0
name = ""
phone = ""
Characteristics = []
I need to parse the JSON data and instantiate appropriate Classes. The Classes are self-explanatory: i.e. Person has an array of Character classes.
How do I instantiate these and store data appropriately?
Also, how will I access particular Person data? i.e. Person's details and characteristics
If you need to parse a JSON string that returns a dictionary, then you can use the json. loads() method. If you need to parse a JSON file that returns a dictionary, then you can use the json. load() method.
Method 2: Writing JSON to a file in Python using json.dump() Another way of writing JSON to a file is by using json.dump() method The JSON package has the “dump” function which directly writes the dictionary to a file in the form of JSON, without needing to convert it into an actual JSON object.
Create a python file named json1.py with the following script. JSON module is used to read any JSON data using python script. open() method is used to read student. json file and load() method is used to store the data into the variable, data.
Take a look at colander; it makes turning a JSON data structure into Python objects dead easy.
You define a schema:
import colander
class Characteristic(colander.MappingSchema):
id = colander.SchemaNode(colander.Int(),
validator=colander.Range(0, 9999))
name = colander.SchemaNode(colander.String())
rating = colander.SchemaNode(colander.String())
class Characteristics(colander.SequenceSchema):
characteristic = Characteristic()
class Person(colander.MappingSchema):
id = colander.SchemaNode(colander.Int(),
validator=colander.Range(0, 9999))
name = colander.SchemaNode(colander.String())
phone = colander.SchemaNode(colander.String())
characteristics = Characteristics()
class Data(colander.SequenceSchema):
person = Person()
then pass in your JSON data structure using the following:
deserialized = Data.deserialize(json.loads(json_string))
If you are writing in python 3.6+, the easiest is probably to use marshmallow-dataclass :
from marshmallow_dataclass import dataclass
from typing import List
@dataclass
class Character:
id : int
name : str
rating : str
@dataclass
class Person:
id : int
name : str
phone : str
characteristics : List[Character]
my_person = Person.Schema().loads(json_str)
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