【问题标题】:Creating python object from json从 json 创建 python 对象
【发布时间】:2019-06-02 22:12:30
【问题描述】:

我有包含此类信息的 json 文件

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

及以下班

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

如何创建类对象并将数据从 json 传输到类实例?

我试过了

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

【问题讨论】:

  • 你能分享一下你到目前为止的尝试吗
  • 我很困惑,你是想将数据从 GasCar() 传输到 JSON,还是从 JSON 传输到 GasCar?
  • 从 json 到 GasCar

标签: python json


【解决方案1】:

您可以使用json.loads (Docs) 将 JSON 对象读入字典,然后将字典作为构造函数传递给您的类。如果您需要更多解释,请告诉我。

【讨论】:

    【解决方案2】:

    python json 模块无法解析您的 JSON,因为 100, 中的尾随逗号如果您想解决这个问题,您可以参考 this 答案。 但是假设json如下:

    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
    

    您可以像这样创建汽车对象:

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

    或者,如果您想要所有汽车的列表:

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

    【讨论】:

      【解决方案3】:

      我喜欢用更通用的方式来完成这项工作。即时将python对象粘合在一起并将它们序列化为json,反之亦然,获取一个JSON字符串并从中制作一个“Value-Container”对象(没有方法等)-我想知道程序员如何在没有的情况下生活:-)

      也许不是世界上最好的代码,请提出您的建议,但我已经这样做了 7 年了(也可以在 jython 中运行,性能也“不错”): (请debug查看最后“po1”的结构):

      # 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)
      

      【讨论】:

      • ... 我找到了目标相同的 jsonpickle。也许是更好的方法。
      猜你喜欢
      • 2022-01-22
      • 1970-01-01
      • 2014-01-14
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      • 2014-07-12
      • 1970-01-01
      • 2018-08-11
      相关资源
      最近更新 更多