Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JSON and store data in Python Class

Tags:

python

json

class

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

like image 702
Kartik Rokde Avatar asked Sep 11 '12 13:09

Kartik Rokde


People also ask

How do I parse a JSON in Python?

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.

How do I save JSON data in Python?

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.

How does Python store JSON data in a variable?

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.


2 Answers

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)) 
like image 62
Martijn Pieters Avatar answered Oct 14 '22 12:10

Martijn Pieters


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)
like image 26
lovasoa Avatar answered Oct 14 '22 12:10

lovasoa