在python中解码来自JSON的对象

时间:2017-05-10 20:13:42

标签: python json

我有一个看起来像这样的课程:

class Car:
def __init__(self, name, colour, wheels):
    self.name = name
    self.colour = colour
    self.wheels = wheels

我想从JSON文件创建上述类的对象,它看起来像这样,但有很多条目:

  "Cars":[
  {
  "name": "Golf",
  "colour": "red",
  "wheels": 4,
  },
  {
  "name": "Up",
  "colour": "green",
  "wheels": 3,
  }
  ]

然后将它们添加到具有布局{" name":object}的字典中。我已经查看了可用的不同教程和示例,但大多数似乎都是关于转储对象,而不是将它们拉出来并从中重新创建对象。

2 个答案:

答案 0 :(得分:1)

如果您的文件确保您有相同的订单(名称,颜色,轮子)和相同的尺寸(3个项目),您可以使用以下内容:

JSON文件(foo.json):

{"Cars":{
"Golf":{
  "name": "Golf",
  "colour": "red",
  "wheels": 4
  },  
"Robin": {
  "name": "Up",
  "colour": "green",
  "wheels": 3
  }
  } 
}


>>> import json
>>> import collections
>>> data = ''.join(i.replace('\n','') for i in open('foo.json').readlines())
>>> decoder = json.JSONDecoder(object_pairs_hook=collections.OrderedDict)
>>>
>>> class Car(object):
...  def __init__(self, name, colour, wheels):
...     self.name = name
...     self.colour = colour
...     self.wheels = wheels
... 
>>> j = decoder.decode(data)
>>> 
>>> out_dict = {car:Car(*j['Cars'][car].values()) for car in j['Cars']}
>>>
>>> golf = out_dict['Golf']
>>> golf.name
u'Golf'
>>> golf.colour
u'red'
>>> golf.wheels
4

答案 1 :(得分:1)

import json

class Car(object):
    def __init__(self, name, colour, wheels):
        self.name = name
        self.colour = colour
        self.wheels = wheels

    def __repr__(self):
        return 'A {} {} with {} wheels'.format(self.colour, self.name, self.wheels)

raw = '{"name": "Ferrari", "colour": "red", "wheels": 4}'
decoded = json.loads(raw)
car = Car(**decoded)
print(car)

您可以使用**语法将字典转换为命名参数。基本上它转换为这样的调用:Car(name="Ferrari", colour="red", wheels="4")。所以你不必担心订单。

如果您有一个列表,您当然可以映射JSON结果:

raw = '[{...}, {...}]'
decoded = json.loads(raw)
cars = [Car(**d) for d in decoded]
print(cars)