8

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

5
  • 1
    Similar question: stackoverflow.com/questions/3847399/… Commented Sep 11, 2012 at 13:15
  • 1
    Note that your JSON example is rather malformed. Apart from the odd quotes you've used, you cannot have multiple Character keys in the Charecteristics object either. Commented Sep 11, 2012 at 13:20
  • I've cleaned up your JSON to actually be valid; note that I've turned both the group of persons and group of characteristics into lists (as they would normally be). Commented Sep 11, 2012 at 13:32
  • @Tichodroma: I'll surely do more research the next time.. Sorry I didnt find the similar question at my first few tries. Commented Sep 11, 2012 at 17:10
  • See JSON data into a Python object Commented Feb 4, 2021 at 21:46

2 Answers 2

13

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

4 Comments

Thanks.. :-) I'm new to Python but have to work with web services,, so using dJango.. Pls consider me amateur.. One more question..
Thats not dead easy. Dead easy would be if it generated python classes given a particular JSON string.
@Vanuan anything that does that?
@Jonathan The closest is this github.com/cwacek/python-jsonschema-objects But it still requires specifying types for each field.
6

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)

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.