1

I have a class that looks like this:

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

I would like to create objects of the above class from the JSON file, which looks like this but with many entries:

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

And then add them to a dictionary with the layout {"name":object}. I've looked at the different tutorials and examples available, but most seems to be about dumping objects, not pulling them out and recreating objects from them.

3
  • Does the key in the Cars object in the JSON mean anything? For example, the second object has a key of Robin, should anything be done with that? Commented May 10, 2017 at 20:19
  • Thanks for the comment. No, it's just extra junk - it's probably easier for me to just edit it out in the JSON file so I'll amend the example. Commented May 10, 2017 at 20:26
  • Have you tried anything on your own yet? Do you know how to instantiate classes and how to index dictionaries? Or, is one of those two things tripping you up? Also, your modified example JSON is invalid. You should change the Cars value to be a list rather than an object (eg. [ instead of {). Commented May 10, 2017 at 20:29

2 Answers 2

1

If your file ensures that you have aways same order (name, colour, wheels) and same size (3 items), you can use something like this:

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

1 Comment

This works great thank you, unfortunately I have tons of different cars to loop through, how would be best to put this into a loop?
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)

You can use the ** syntax to turn a dictionary into named parameters. Basically it transforms to a call like this: Car(name="Ferrari", colour="red", wheels="4"). So you don't need to worry about the order.

If you have a list, you can of course map over the JSON result:

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

5 Comments

This looks good, but I'm trying to load from an external JSON file - I've tried to modify it but get: ValueError: No JSON object could be decoded Any ideas?
json.load(open("filename.json")) then. Make sure your json is valid. Search the web for a json validator.
Trading commas are not allowed in JSON. Remove them from after the wheel count.
Tried this, and have gotten 'TypeError: type object argument after ** must be a mapping, not unicode' - I've validated using JSONlint and removed the offending commas but the error still appears.
Apparently whatever variable you used with ** contains a string (Unicode), not a dictionary. Are you iterating over you decoded["Cars"] dictionary using .values() or .items() correctly?

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.