简体   繁体   中英

Creating python object from json

I have json file with such information

{
  "cars" : [{
    "model" : " BMW",
    "gas" : 100,
  },
  {
    "model" : "LADA",
    "gas" : 150
  },
  {
    "model" : "SUZUKI",
    "gas" : 70
  }]
}

and following class

class GasCar(Car):
    def __init__(self, model=None, gas=None):
        super(GasCar, self).__init__()
        self.gas = gas
        self.model = model

how can I create class object and transfer data from json to class instance?

I tried this

car = GasCar()
s = json.dumps(car)
s = json.dumps(car.__dict__)

Your JSON cannot be parsed by python json module because of the trailing comma in 100, you may refer to this answer if you want to solve that. But assuming that the json is as follows:

import json
class GasCar():
    def __init__(self, model=None, gas=None):
        super(GasCar, self).__init__()
        self.gas = gas
        self.model = model

cars = """{
  "cars" : [{
    "model" : "BMW",
    "gas" : 100
  },
  {
    "model" : "LADA",
    "gas" : 150
  },
  {
    "model" : "SUZUKI",
    "gas" : 70
  }]
}"""

json_cars = json.loads(cars)
cars = json_cars["cars"] # gets "cars" list

You can create a car object like this:

car_object1 = GasCar(cars[0]["model"], cars[0]["gas"])
print(car_object1.model) # prints "BMW"

Or if you want a list of all cars:

car_objects = [GasCar(car["model"], car["gas"]) for car in cars]

You could read the JSON object into dictionaries with json.loads ( Docs ), and then pass the dictionaries as constructors to you class. Let me know if you need more explanation.

I love a more generic way to do this job. Gluing together python objects on the fly and serializing them to json and vice versa getting a JSON string an make a "Value-Container"-object out of it (without methods etc.) - I wonder how programmers can live without :-)

Maybe not the best code in the world and please make your suggestions, but I am doing it for 7 years now that way (runs in jython as well, performance also "ok"): (please debug to see the structure of "po1" at the end):

# coding: UTF-8

import json

import types

def obj2dict(pp):
    if type(pp) is types.TupleType:
        olist=[]
        for p in pp:
            olist.append(obj2dict(p))
        return tuple(olist)
    if type(pp) is types.ListType:
        olist=[]
        for p in pp:
            olist.append(obj2dict(p))
        return olist

    if type(pp) is types.DictionaryType:
        odict={}
        for k,val in pp.items():
            odict[k]=obj2dict(val)
        return odict
    if type(pp) is types.InstanceType:
        odict={}
        for m in pp.__dict__:
            val=getattr(pp,m)
            odict[m]=obj2dict(val)
        return odict

        for m in dir(pp):
            if not m.startswith("_"): 
                val=getattr(pp,m)
                odict[m]=obj2dict(val)
        return odict
    return pp

class CONT:pass

def toFloat(inp):
    return float(inp.replace(",",".")) 


def dict2obj(pp):
    if type(pp) is types.ListType:
        olist=[]
        for p in pp:
            olist.append(dict2obj(p))
        return olist
    if type(pp) is types.DictionaryType:
        oinst=CONT()
        for (k,v) in pp.items():
            val=dict2obj(v)
            setattr(oinst,k,val)
        return oinst
    try:
        pp=toFloat(pp)
    except:pass
    return pp

def dumps(pp):
    return json.dumps(obj2dict(pp)) #,ensure_ascii=False)
def loads(pp):
    return dict2obj(json.loads(pp))  #,ensure_ascii=False))


if __name__ == "__main__":
    jstring="""{
  "cars" : [{
    "model" : " BMW",
    "gas" : 100
  },
  {
    "model" : "LADA",
    "gas" : 150
  },
  {
    "model" : "SUZUKI",
    "gas" : 70
  }]
}"""
    po1=loads(jstring)
    po=CONT()
    po.model="Toyota"
    po.gas=88
    print dumps(po)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM