344

I want to convert JSON data into a Python object.

I receive JSON data objects from the Facebook API, which I want to store in my database.

My current View in Django (Python) (request.POST contains the JSON):

response = request.POST
user = FbApiUser(user_id = response['id'])
user.name = response['name']
user.username = response['username']
user.save()
  • This works fine, but how do I handle complex JSON data objects?
  • Wouldn't it be much better if I could somehow convert this JSON object into a Python object for easy use?
codeforester
  • 28,846
  • 11
  • 78
  • 104
Sai Krishna
  • 6,057
  • 6
  • 26
  • 40
  • Typically JSON gets converted to vanilla lists or dicts. Is that what you want? Or are you hoping to convert JSON straight to a custom type? – Shakakai Jul 05 '11 at 07:05
  • I want to convert it into an object, something I can access using the "." . Like from the above example -> reponse.name, response.education.id etc.... – Sai Krishna Jul 05 '11 at 07:09
  • 61
    Using `dict`s is a weak-sauce way to do object-oriented programming. Dictionaries are a very poor way to communicate expectations to readers of your code. Using a dictionary, how can you clearly and reusably specify that some dictionary keys-value pairs are required, while others aren't? What about confirming that a given value is in the acceptable range or set? What about functions that are specific to the type of object you are working with (aka methods)? Dictionaries are handy and versatile, but too many devs act like they forgot Python is an object oriented language for a reason. – Stew Apr 15 '16 at 16:20
  • 2
    There is a python library for this https://github.com/jsonpickle/jsonpickle (commenting since answer is too below in the thread and wont be reachable.) – best wishes May 10 '19 at 04:55

24 Answers24

469

UPDATE

With Python3, you can do it in one line, using SimpleNamespace and object_hook:

import json
from types import SimpleNamespace

data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}'

# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(data, object_hook=lambda d: SimpleNamespace(**d))
print(x.name, x.hometown.name, x.hometown.id)

OLD ANSWER (Python2)

In Python2, you can do it in one line, using namedtuple and object_hook (but it's very slow with many nested objects):

import json
from collections import namedtuple

data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}'

# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(data, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))
print x.name, x.hometown.name, x.hometown.id

or, to reuse this easily:

def _json_object_hook(d): return namedtuple('X', d.keys())(*d.values())
def json2obj(data): return json.loads(data, object_hook=_json_object_hook)

x = json2obj(data)

If you want it to handle keys that aren't good attribute names, check out namedtuple's rename parameter.

DS.
  • 17,804
  • 4
  • 43
  • 46
  • 12
    this may result in a Value error, ValueError: Type names and field names cannot start with a number: '123' – PvdL Apr 11 '14 at 21:01
  • 3
    As a newbie to Python, I'm interested if this is a save thing also when security is an issue. – benjist Jul 05 '15 at 22:15
  • It's easy for the user to supply data that will cause this to raise an exception (whether as invalid json, or an invalid attribute name -- see the note at the end about `rename` parameter). But other than the possibility of an exception, I don't see any potential attacks here. – DS. Jul 06 '15 at 01:46
  • You will find that for unwrapping data from Parse.com, rename = true will be required as DS hinted if you store complex objects. def _json_object_hook(d): return namedtuple('X', d.keys())(*d.values(),rename=true) – Jitendra Kulkarni Aug 14 '15 at 17:02
  • This turned out to be perfectly cromulent for my tiny, simple, mocking use-case. Thankies! – mallyvai Nov 06 '15 at 18:38
  • 12
    This creates a new *different* class each time encountering a JSON object while parsing, right? – fikr4n Jan 15 '16 at 03:21
  • 2
    Interesting. I thought relying on `d.keys()` and `d.values()` iterating in the same order is not guaranteed, but I was wrong. The [docs](https://docs.python.org/3.5/library/stdtypes.html#dictionary-view-objects) say: "If keys, values and items views are iterated over with no intervening modifications to the dictionary, the order of items will directly correspond.". Good to know for such small, local code blocks. I'd add a comment though to explicitly alert maintainers of code of such a dependency. – cfi Jun 01 '16 at 07:33
  • Concerning the snippet that @JitendraKulkarni posted above: The `rename=True` argument has to supplied to the `namedtuple` constructor, i.e., `def _json_object_hook(d): return namedtuple('X', d.keys(),rename=True)(*d.values()) `. – Thomas Auzinger Sep 06 '16 at 14:56
  • Is reverse operation possible? – enigmaticPhysicist Feb 19 '18 at 22:28
  • 2
    I am not aware of any nice general-purpose reverse operation. Any individual namedtuple can be turned to a dict using `x._asdict()`, which might help for simple cases. – DS. Feb 21 '18 at 05:04
  • It takes lot of time its good if you directly can use jsonarray or dict – SuperUser Apr 04 '18 at 10:17
  • 1
    For loading generic data into typed python datatypes I wrote a module called `typedload`. It supports nesting, lists, sets, unions and many other things. – LtWorf Sep 19 '18 at 21:37
  • 1
    It returns named tuple not custom class instance. – IMXQD Jan 08 '19 at 09:33
  • How could this be done if our `data` was already a `dict`, not `str`? I mean without needing to call `json.loads`. – B Faley Feb 06 '19 at 07:07
  • Without `json.loads`, I don't know of an easy way to convert recursively. To convert one level, you can use `namedtuple('X', data.keys())(*data.values())` – DS. Feb 07 '19 at 08:11
  • 1
    @BFaley perhaps just a `json.dumps()`? – lingfish Jul 23 '20 at 08:19
  • 1
    Creating a new class for every object you deserialize is absurdly inefficient. Each namedtuple class takes a ton of extra time and memory to create. This can slow down deserialization by multiple orders of magnitude. – user2357112 supports Monica Sep 13 '20 at 09:46
  • Literally, I tried it, and [I observed over a 100x performance penalty in timing tests](https://ideone.com/rvLI3H). The output also consumes over an order of magnitude more memory, though this is harder to measure. (It's not as simple as calling `sys.getsizeof` - that doesn't do what people usually think.) – user2357112 supports Monica Sep 13 '20 at 09:59
  • That's a good example, it is indeed pretty terrible with many objects. I added an update since Python3 provides a similar utility (SimpleNamespace) that makes this much more efficient. – DS. Sep 14 '20 at 15:28
138

Check out the section titled Specializing JSON object decoding in the json module documentation. You can use that to decode a JSON object into a specific Python type.

Here's an example:

class User(object):
    def __init__(self, name, username):
        self.name = name
        self.username = username

import json
def object_decoder(obj):
    if '__type__' in obj and obj['__type__'] == 'User':
        return User(obj['name'], obj['username'])
    return obj

json.loads('{"__type__": "User", "name": "John Smith", "username": "jsmith"}',
           object_hook=object_decoder)

print type(User)  # -> <type 'type'>

Update

If you want to access data in a dictionary via the json module do this:

user = json.loads('{"__type__": "User", "name": "John Smith", "username": "jsmith"}')
print user['name']
print user['username']

Just like a regular dictionary.

martineau
  • 99,260
  • 22
  • 139
  • 249
Shakakai
  • 3,425
  • 1
  • 14
  • 18
  • 1
    Hey, I was just reading up and I realized that dictionaries will totally do, only I was wondering how to convert JSON objects into dictionaries and how do I access this data from the dictionary? – Sai Krishna Jul 05 '11 at 07:22
  • Awesome, it's almost clear, just wanted to know one more little thing that if there's this object -> { 'education' : { 'name1' : 456 , 'name2' : 567 } }, how do i access this data? – Sai Krishna Jul 05 '11 at 07:28
  • it'd just be topLevelData['education']['name1'] ==> 456. make sense? – Shakakai Jul 05 '11 at 07:31
  • 1
    @Ben: I think your comment is inappropriate. Of all the answers here currently it is the only one to get the classes right. Which means: It's a one-pass operation and the result uses the correct types. Pickle itself is for different applications than JSON (binary versus textual rep) and jsonpickle is a nonstandard lib. I'd be interested to see how you solve the issue that the std json lib does not provide the upper parse tree to the object hook – cfi Jun 01 '16 at 07:43
  • I have to agree with @Ben on this. This is a really bad solution. Not scalable at all. You'll need to maintain fields' names as string and as field. If you'll want to refactor your fields the decoding will fail (of course the already serialized data will no longer be relevant anyway). The same concept is already implemented well with [jsonpickle](http://jsonpickle.github.io/) – Guy Aug 07 '16 at 20:12
  • This is quite messy and complicated and I can't recommend this approach in 2020. – Jurass Mar 15 '20 at 16:56
106

This is not code golf, but here is my shortest trick, using types.SimpleNamespace as the container for JSON objects.

Compared to the leading namedtuple solution, it is:

  • probably faster/smaller as it does not create a class for each object
  • shorter
  • no rename option, and probably the same limitation on keys that are not valid identifiers (uses setattr under the covers)

Example:

from __future__ import print_function
import json

try:
    from types import SimpleNamespace as Namespace
except ImportError:
    # Python 2.x fallback
    from argparse import Namespace

data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}'

x = json.loads(data, object_hook=lambda d: Namespace(**d))

print (x.name, x.hometown.name, x.hometown.id)
Dan Lenski
  • 67,458
  • 11
  • 63
  • 115
eddygeek
  • 3,270
  • 2
  • 20
  • 28
  • 2
    By the way, the serialization library Marshmallow offers a similar feature with its `@post_load` decorator. https://marshmallow.readthedocs.io/en/latest/quickstart.html#deserializing-to-objects – Taylor Edmiston Sep 18 '16 at 15:58
  • 4
    To avoid the dependency on argparse: replace the argparse import with `from types import SimpleNamespace` and use: `x = json.loads(data, object_hook=lambda d: SimpleNamespace(**d))` – maxschlepzig Dec 06 '16 at 07:59
  • 10
    This is the most elegant solution, should be at the top. – ScalaWilliam Dec 28 '16 at 13:05
  • 4
    Edited to use @maxschlepzig's solution when running under Python 3.x (`types.SimpleNamespace` doesn't exist in 2.7, unfortunately). – Dan Lenski Feb 14 '17 at 21:18
  • This is by far the cleanest approach. The only thing to be pointed out that SimpleNamespace will parse JSON-booleans "true" or "false" literally - in those cases 1s and 0s can be used in the JSON to establish truthiness instead. – Vineet Bansal Jan 26 '19 at 16:07
  • 1
    why `print_function`? – chwi Oct 07 '19 at 20:26
  • @VineetBansal: Whatever effect you're talking about isn't something that SimpleNamespace does. Something might be wrong with your JSON. – user2357112 supports Monica Sep 13 '20 at 09:49
104

You could try this:

class User(object):
    def __init__(self, name, username):
        self.name = name
        self.username = username

import json
j = json.loads(your_json)
u = User(**j)

Just create a new object, and pass the parameters as a map.

Note: It does not work for nested classes.

cmaluenda
  • 1,285
  • 1
  • 9
  • 13
42

Here's a quick and dirty json pickle alternative

import json

class User:
    def __init__(self, name, username):
        self.name = name
        self.username = username

    def to_json(self):
        return json.dumps(self.__dict__)

    @classmethod
    def from_json(cls, json_str):
        json_dict = json.loads(json_str)
        return cls(**json_dict)

# example usage
User("tbrown", "Tom Brown").to_json()
User.from_json(User("tbrown", "Tom Brown").to_json()).to_json()
ubershmekel
  • 9,570
  • 6
  • 62
  • 78
  • 1
    This is not good approach. At first to_json and from_json should not be placed in your class. At second it will not work work for nested classes. – Jurass Mar 15 '20 at 16:59
17

For complex objects, you can use JSON Pickle

Python library for serializing any arbitrary object graph into JSON. It can take almost any Python object and turn the object into JSON. Additionally, it can reconstitute the object back into Python.

Paolo
  • 16,171
  • 20
  • 78
  • 110
sputnikus
  • 553
  • 1
  • 3
  • 12
  • 6
    I think [jsonstruct](https://github.com/initialxy/jsonstruct) is better. `jsonstruct originally a fork of jsonpickle (Thanks guys!). The key difference between this library and jsonpickle is that during deserialization, jsonpickle requires Python types to be recorded as part of the JSON. This library intends to remove this requirement, instead, requires a class to be passed in as an argument so that its definition can be inspected. It will then return an instance of the given class. This approach is similar to how Jackson (of Java) works.` – Abhishek Gupta Jan 20 '16 at 16:57
  • 3
    The problems with jsonstruct is that it doesn't appear to be maintained (in fact, it looks abandoned) and it fails to convert a list of objects, like `'[{"name":"object1"},{"name":"object2"}]'`. jsonpickle doesn't handle it very well, either. – Mr. Lance E Sloan Jul 31 '16 at 15:36
  • 1
    I have no idea why this answer isn't getting more votes. Most other solution are quite out-there. Someone developed a great library for JSON de/serialization - why not use it? In addition, seems to be working fine with lists - what was your issue with it @LS ? – Guy Aug 07 '16 at 19:59
  • 1
    @guyarad, the problem is: x= jsonpickle.decode('[{"name":"object1"},{"name":"object2"}]') gives a list of dictionaries ([{'name': 'object1'}, {'name': 'object2'}]), not a list of objects with properties (x[0].name == 'object1'), which is what the original question required. To get that, I ended up using the object_hook/Namespace approach suggested by eddygeek, but the quick/dirty approach by ubershmekel looks good, too. I think I could use object_hook with jsonpickle's set_encoder_options() (undocumented!), but it would take more code than the basic json module. I'd love to be proven wrong! – Mr. Lance E Sloan Aug 09 '16 at 15:48
  • @LS if you have no control over the input, which is truly what the OP asked, jsonpickle isn't ideal since it expect the actual type in each level (and will assume basic types if missing). Both solutions are "cute". – Guy Aug 09 '16 at 18:18
14

If you're using Python 3.5+, you can use jsons to serialize and deserialize to plain old Python objects:

import jsons

response = request.POST

# You'll need your class attributes to match your dict keys, so in your case do:
response['id'] = response.pop('user_id')

# Then you can load that dict into your class:
user = jsons.load(response, FbApiUser)

user.save()

You could also make FbApiUser inherit from jsons.JsonSerializable for more elegance:

user = FbApiUser.from_json(response)

These examples will work if your class consists of Python default types, like strings, integers, lists, datetimes, etc. The jsons lib will require type hints for custom types though.

R H
  • 1,059
  • 1
  • 11
  • 11
10

If you are using python 3.6+, you can use marshmallow-dataclass. Contrarily to all the solutions listed above, it is both simple, and type safe:

from marshmallow_dataclass import dataclass

@dataclass
class User:
    name: str

user = User.Schema().load({"name": "Ramirez"})
lovasoa
  • 5,068
  • 30
  • 38
  • `TypeError: make_data_class() got an unexpected keyword argument 'many'` – JOhn Aug 27 '19 at 19:12
  • 1
    @JOhn : You should open an issue with a reproducible test case in https://github.com/lovasoa/marshmallow_dataclass/issues – lovasoa Aug 28 '19 at 08:15
6

Improving the lovasoa's very good answer.

If you are using python 3.6+, you can use:
pip install marshmallow-enum and
pip install marshmallow-dataclass

Its simple and type safe.

You can transform your class in a string-json and vice-versa:

From Object to String Json:

    from marshmallow_dataclass import dataclass
    user = User("Danilo","50","RedBull",15,OrderStatus.CREATED)
    user_json = User.Schema().dumps(user)
    user_json_str = user_json.data

From String Json to Object:

    json_str = '{"name":"Danilo", "orderId":"50", "productName":"RedBull", "quantity":15, "status":"Created"}'
    user, err = User.Schema().loads(json_str)
    print(user,flush=True)

Class definitions:

class OrderStatus(Enum):
    CREATED = 'Created'
    PENDING = 'Pending'
    CONFIRMED = 'Confirmed'
    FAILED = 'Failed'

@dataclass
class User:
    def __init__(self, name, orderId, productName, quantity, status):
        self.name = name
        self.orderId = orderId
        self.productName = productName
        self.quantity = quantity
        self.status = status

    name: str
    orderId: str
    productName: str
    quantity: int
    status: OrderStatus
danilo
  • 3,651
  • 5
  • 25
  • 33
5

dacite may also be a solution for you, it supports following features:

  • nested structures
  • (basic) types checking
  • optional fields (i.e. typing.Optional)
  • unions
  • forward references
  • collections
  • custom type hooks

https://pypi.org/project/dacite/

from dataclasses import dataclass
from dacite import from_dict


@dataclass
class User:
    name: str
    age: int
    is_active: bool


data = {
    'name': 'John',
    'age': 30,
    'is_active': True,
}

user = from_dict(data_class=User, data=data)

assert user == User(name='John', age=30, is_active=True)
BernhardS
  • 716
  • 2
  • 7
  • 21
5

I have written a small (de)serialization framework called any2any that helps doing complex transformations between two Python types.

In your case, I guess you want to transform from a dictionary (obtained with json.loads) to an complex object response.education ; response.name, with a nested structure response.education.id, etc ... So that's exactly what this framework is made for. The documentation is not great yet, but by using any2any.simple.MappingToObject, you should be able to do that very easily. Please ask if you need help.

cfi
  • 9,815
  • 7
  • 51
  • 93
sebpiq
  • 6,764
  • 8
  • 44
  • 65
  • Sebpiq, have installed any2any and am having troubles understanding the intended sequence of method calls. Could you give a simple example of converting a dictionary to a Python object with a property for each key? – sansjoe May 07 '12 at 17:00
  • Hi @sansjoe ! If you have installed it from pypi, the version is completely out of date, I have made a complete refactoring a few weeks ago. You should use the github version (I need to make a proper release !) – sebpiq May 09 '12 at 06:51
  • I installed it from pypy because the github said to install it from pypy. Also, you said pypy was out of date months ago.. It didn't work :( I filed a bug report tho! https://github.com/sebpiq/any2any/issues/11 – sneilan Sep 01 '12 at 03:19
4

Since noone provided an answer quite like mine, I am going to post it here.

It is a robust class that can easily convert back and forth between json str and dict that I have copied from my answer to another question:

import json

class PyJSON(object):
    def __init__(self, d):
        if type(d) is str:
            d = json.loads(d)

        self.from_dict(d)

    def from_dict(self, d):
        self.__dict__ = {}
        for key, value in d.items():
            if type(value) is dict:
                value = PyJSON(value)
            self.__dict__[key] = value

    def to_dict(self):
        d = {}
        for key, value in self.__dict__.items():
            if type(value) is PyJSON:
                value = value.to_dict()
            d[key] = value
        return d

    def __repr__(self):
        return str(self.to_dict())

    def __setitem__(self, key, value):
        self.__dict__[key] = value

    def __getitem__(self, key):
        return self.__dict__[key]

json_str = """... json string ..."""

py_json = PyJSON(json_str)
Božo Stojković
  • 2,763
  • 1
  • 19
  • 46
3

While searching for a solution, I've stumbled upon this blog post: https://blog.mosthege.net/2016/11/12/json-deserialization-of-nested-objects/

It uses the same technique as stated in previous answers but with a usage of decorators. Another thing I found useful is the fact that it returns a typed object at the end of deserialisation

class JsonConvert(object):
    class_mappings = {}

    @classmethod
    def class_mapper(cls, d):
        for keys, cls in clsself.mappings.items():
            if keys.issuperset(d.keys()):   # are all required arguments present?
                return cls(**d)
        else:
            # Raise exception instead of silently returning None
            raise ValueError('Unable to find a matching class for object: {!s}'.format(d))

    @classmethod
    def complex_handler(cls, Obj):
        if hasattr(Obj, '__dict__'):
            return Obj.__dict__
        else:
            raise TypeError('Object of type %s with value of %s is not JSON serializable' % (type(Obj), repr(Obj)))

    @classmethod
    def register(cls, claz):
        clsself.mappings[frozenset(tuple([attr for attr,val in cls().__dict__.items()]))] = cls
        return cls

    @classmethod
    def to_json(cls, obj):
        return json.dumps(obj.__dict__, default=cls.complex_handler, indent=4)

    @classmethod
    def from_json(cls, json_str):
        return json.loads(json_str, object_hook=cls.class_mapper)

Usage:

@JsonConvert.register
class Employee(object):
    def __init__(self, Name:int=None, Age:int=None):
        self.Name = Name
        self.Age = Age
        return

@JsonConvert.register
class Company(object):
    def __init__(self, Name:str="", Employees:[Employee]=None):
        self.Name = Name
        self.Employees = [] if Employees is None else Employees
        return

company = Company("Contonso")
company.Employees.append(Employee("Werner", 38))
company.Employees.append(Employee("Mary"))

as_json = JsonConvert.to_json(company)
from_json = JsonConvert.from_json(as_json)
as_json_from_json = JsonConvert.to_json(from_json)

assert(as_json_from_json == as_json)

print(as_json_from_json)
enazar
  • 31
  • 3
2

Modifying @DS response a bit, to load from a file:

def _json_object_hook(d): return namedtuple('X', d.keys())(*d.values())
def load_data(file_name):
  with open(file_name, 'r') as file_data:
    return file_data.read().replace('\n', '')
def json2obj(file_name): return json.loads(load_data(file_name), object_hook=_json_object_hook)

One thing: this cannot load items with numbers ahead. Like this:

{
  "1_first_item": {
    "A": "1",
    "B": "2"
  }
}

Because "1_first_item" is not a valid python field name.

Valtoni Boaventura
  • 1,258
  • 11
  • 13
2

Expanding on DS's answer a bit, if you need the object to be mutable (which namedtuple is not), you can use the recordclass library instead of namedtuple:

import json
from recordclass import recordclass

data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}'

# Parse into a mutable object
x = json.loads(data, object_hook=lambda d: recordclass('X', d.keys())(*d.values()))

The modified object can then be converted back to json very easily using simplejson:

x.name = "John Doe"
new_json = simplejson.dumps(x)
BeneStr
  • 217
  • 2
  • 12
2

The answers given here does not return the correct object type, hence I created these methods below. They also fail if you try to add more fields to the class that does not exist in the given JSON:

def dict_to_class(class_name: Any, dictionary: dict) -> Any:
    instance = class_name()
    for key in dictionary.keys():
        setattr(instance, key, dictionary[key])
    return instance


def json_to_class(class_name: Any, json_string: str) -> Any:
    dict_object = json.loads(json_string)
    return dict_to_class(class_name, dict_object)
Caner
  • 49,709
  • 33
  • 153
  • 169
1

If you're using Python 3.6 or newer, you could have a look at squema - a lightweight module for statically typed data structures. It makes your code easy to read while at the same time providing simple data validation, conversion and serialization without extra work. You can think of it as a more sophisticated and opinionated alternative to namedtuples and dataclasses. Here's how you could use it:

from uuid import UUID
from squema import Squema


class FbApiUser(Squema):
    id: UUID
    age: int
    name: str

    def save(self):
        pass


user = FbApiUser(**json.loads(response))
user.save()
Funkatic
  • 593
  • 1
  • 5
  • 12
1

You can use

x = Map(json.loads(response))
x.__class__ = MyClass

where

class Map(dict):
    def __init__(self, *args, **kwargs):
        super(Map, self).__init__(*args, **kwargs)
        for arg in args:
            if isinstance(arg, dict):
                for k, v in arg.iteritems():
                    self[k] = v
                    if isinstance(v, dict):
                        self[k] = Map(v)

        if kwargs:
            # for python 3 use kwargs.items()
            for k, v in kwargs.iteritems():
                self[k] = v
                if isinstance(v, dict):
                    self[k] = Map(v)

    def __getattr__(self, attr):
        return self.get(attr)

    def __setattr__(self, key, value):
        self.__setitem__(key, value)

    def __setitem__(self, key, value):
        super(Map, self).__setitem__(key, value)
        self.__dict__.update({key: value})

    def __delattr__(self, item):
        self.__delitem__(item)

    def __delitem__(self, key):
        super(Map, self).__delitem__(key)
        del self.__dict__[key]

For a generic, future-proof solution.

Gulzar
  • 10,451
  • 10
  • 52
  • 87
1

I was searching for a solution that worked with recordclass.RecordClass, supports nested objects and works for both json serialization and json deserialization.

Expanding on DS's answer, and expanding on solution from BeneStr, I came up with the following that seems to work:

Code:

import json
import recordclass

class NestedRec(recordclass.RecordClass):
    a : int = 0
    b : int = 0

class ExampleRec(recordclass.RecordClass):
    x : int       = None
    y : int       = None
    nested : NestedRec = NestedRec()

class JsonSerializer:
    @staticmethod
    def dumps(obj, ensure_ascii=True, indent=None, sort_keys=False):
        return json.dumps(obj, default=JsonSerializer.__obj_to_dict, ensure_ascii=ensure_ascii, indent=indent, sort_keys=sort_keys)

    @staticmethod
    def loads(s, klass):
        return JsonSerializer.__dict_to_obj(klass, json.loads(s))

    @staticmethod
    def __obj_to_dict(obj):
        if hasattr(obj, "_asdict"):
            return obj._asdict()
        else:
            return json.JSONEncoder().default(obj)

    @staticmethod
    def __dict_to_obj(klass, s_dict):
        kwargs = {
            key : JsonSerializer.__dict_to_obj(cls, s_dict[key]) if hasattr(cls,'_asdict') else s_dict[key] \
                for key,cls in klass.__annotations__.items() \
                    if s_dict is not None and key in s_dict
        }
        return klass(**kwargs)

Usage:

example_0 = ExampleRec(x = 10, y = 20, nested = NestedRec( a = 30, b = 40 ) )

#Serialize to JSON

json_str = JsonSerializer.dumps(example_0)
print(json_str)
#{
#  "x": 10,
#  "y": 20,
#  "nested": {
#    "a": 30,
#    "b": 40
#  }
#}

# Deserialize from JSON
example_1 = JsonSerializer.loads(json_str, ExampleRec)
example_1.x += 1
example_1.y += 1
example_1.nested.a += 1
example_1.nested.b += 1

json_str = JsonSerializer.dumps(example_1)
print(json_str)
#{
#  "x": 11,
#  "y": 21,
#  "nested": {
#    "a": 31,
#    "b": 41
#  }
#}
Shriram V
  • 994
  • 2
  • 8
  • 15
1

There are multiple viable answers already, but there are some minor libraries made by individuals that can do the trick for most users.

An example would be json2object. Given a defined class, it deserialises json data to your custom model, including custom attributes and child objects.

Its use is very simple. An example from the library wiki:

from json2object import jsontoobject as jo

class Student:
    def __init__(self):
        self.firstName = None
        self.lastName = None
        self.courses = [Course('')]

class Course:
    def __init__(self, name):
        self.name = name

data = '''{
"firstName": "James",
"lastName": "Bond",
"courses": [{
    "name": "Fighting"},
    {
    "name": "Shooting"}
    ]
}
'''

model = Student()
result = jo.deserialize(data, model)
print(result.courses[0].name)
Hoter
  • 35
  • 5
  • 1
    quicktype.io as proposed by Milovan [above](https://stackoverflow.com/a/66054047) does a slightly better job, as it uses more features offered by Python. But sometimes it would be definitely more useful to have a python library! – Night Train Mar 10 '21 at 08:47
1

The lightest solution I think is

import json
from typing import NamedTuple

_j = '{"name":"Иван","age":37,"mother":{"name":"Ольга","age":58},"children":["Маша","Игорь","Таня"],"married": true,' \
     '"dog":null} '


class PersonNameAge(NamedTuple):
    name: str
    age: int


class UserInfo(NamedTuple):
    name: str
    age: int
    mother: PersonNameAge
    children: list
    married: bool
    dog: str


j = json.loads(_j)
u = UserInfo(**j)

print(u.name, u.age, u.mother, u.children, u.married, u.dog)

>>> Ivan 37 {'name': 'Olga', 'age': 58} ['Mary', 'Igor', 'Jane'] True None
lestat_kim
  • 190
  • 1
  • 5
0

Python3.x

The best aproach I could reach with my knowledge was this.
Note that this code treat set() too.
This approach is generic just needing the extension of class (in the second example).
Note that I'm just doing it to files, but it's easy to modify the behavior to your taste.

However this is a CoDec.

With a little more work you can construct your class in other ways. I assume a default constructor to instance it, then I update the class dict.

import json
import collections


class JsonClassSerializable(json.JSONEncoder):

    REGISTERED_CLASS = {}

    def register(ctype):
        JsonClassSerializable.REGISTERED_CLASS[ctype.__name__] = ctype

    def default(self, obj):
        if isinstance(obj, collections.Set):
            return dict(_set_object=list(obj))
        if isinstance(obj, JsonClassSerializable):
            jclass = {}
            jclass["name"] = type(obj).__name__
            jclass["dict"] = obj.__dict__
            return dict(_class_object=jclass)
        else:
            return json.JSONEncoder.default(self, obj)

    def json_to_class(self, dct):
        if '_set_object' in dct:
            return set(dct['_set_object'])
        elif '_class_object' in dct:
            cclass = dct['_class_object']
            cclass_name = cclass["name"]
            if cclass_name not in self.REGISTERED_CLASS:
                raise RuntimeError(
                    "Class {} not registered in JSON Parser"
                    .format(cclass["name"])
                )
            instance = self.REGISTERED_CLASS[cclass_name]()
            instance.__dict__ = cclass["dict"]
            return instance
        return dct

    def encode_(self, file):
        with open(file, 'w') as outfile:
            json.dump(
                self.__dict__, outfile,
                cls=JsonClassSerializable,
                indent=4,
                sort_keys=True
            )

    def decode_(self, file):
        try:
            with open(file, 'r') as infile:
                self.__dict__ = json.load(
                    infile,
                    object_hook=self.json_to_class
                )
        except FileNotFoundError:
            print("Persistence load failed "
                  "'{}' do not exists".format(file)
                  )


class C(JsonClassSerializable):

    def __init__(self):
        self.mill = "s"


JsonClassSerializable.register(C)


class B(JsonClassSerializable):

    def __init__(self):
        self.a = 1230
        self.c = C()


JsonClassSerializable.register(B)


class A(JsonClassSerializable):

    def __init__(self):
        self.a = 1
        self.b = {1, 2}
        self.c = B()

JsonClassSerializable.register(A)

A().encode_("test")
b = A()
b.decode_("test")
print(b.a)
print(b.b)
print(b.c.a)

Edit

With some more of research I found a way to generalize without the need of the SUPERCLASS register method call, using a metaclass

import json
import collections

REGISTERED_CLASS = {}

class MetaSerializable(type):

    def __call__(cls, *args, **kwargs):
        if cls.__name__ not in REGISTERED_CLASS:
            REGISTERED_CLASS[cls.__name__] = cls
        return super(MetaSerializable, cls).__call__(*args, **kwargs)


class JsonClassSerializable(json.JSONEncoder, metaclass=MetaSerializable):

    def default(self, obj):
        if isinstance(obj, collections.Set):
            return dict(_set_object=list(obj))
        if isinstance(obj, JsonClassSerializable):
            jclass = {}
            jclass["name"] = type(obj).__name__
            jclass["dict"] = obj.__dict__
            return dict(_class_object=jclass)
        else:
            return json.JSONEncoder.default(self, obj)

    def json_to_class(self, dct):
        if '_set_object' in dct:
            return set(dct['_set_object'])
        elif '_class_object' in dct:
            cclass = dct['_class_object']
            cclass_name = cclass["name"]
            if cclass_name not in REGISTERED_CLASS:
                raise RuntimeError(
                    "Class {} not registered in JSON Parser"
                    .format(cclass["name"])
                )
            instance = REGISTERED_CLASS[cclass_name]()
            instance.__dict__ = cclass["dict"]
            return instance
        return dct

    def encode_(self, file):
        with open(file, 'w') as outfile:
            json.dump(
                self.__dict__, outfile,
                cls=JsonClassSerializable,
                indent=4,
                sort_keys=True
            )

    def decode_(self, file):
        try:
            with open(file, 'r') as infile:
                self.__dict__ = json.load(
                    infile,
                    object_hook=self.json_to_class
                )
        except FileNotFoundError:
            print("Persistence load failed "
                  "'{}' do not exists".format(file)
                  )


class C(JsonClassSerializable):

    def __init__(self):
        self.mill = "s"


class B(JsonClassSerializable):

    def __init__(self):
        self.a = 1230
        self.c = C()


class A(JsonClassSerializable):

    def __init__(self):
        self.a = 1
        self.b = {1, 2}
        self.c = B()


A().encode_("test")
b = A()
b.decode_("test")
print(b.a)
# 1
print(b.b)
# {1, 2}
print(b.c.a)
# 1230
print(b.c.c.mill)
# s
0

JSON to python object

The follwing code creates dynamic attributes with the objects keys recursively.

JSON object - fb_data.json:

{
    "name": "John Smith",
    "hometown": {
        "name": "New York",
        "id": 123
    },
    "list": [
        "a",
        "b",
        "c",
        1,
        {
            "key": 1
        }
    ],
    "object": {
        "key": {
            "key": 1
        }
    }
}

On the conversion we have 3 cases:

  • lists
  • dicts (new object)
  • bool, int, float and str
import json


class AppConfiguration(object):
    def __init__(self, data=None):
        if data is None:
            with open("fb_data.json") as fh:
                data = json.loads(fh.read())
        else:
            data = dict(data)

        for key, val in data.items():
            setattr(self, key, self.compute_attr_value(val))

    def compute_attr_value(self, value):
        if isinstance(value, list):
            return [self.compute_attr_value(x) for x in value]
        elif isinstance(value, dict):
            return AppConfiguration(value)
        else:
            return value


if __name__ == "__main__":
    instance = AppConfiguration()

    print(instance.name)
    print(instance.hometown.name)
    print(instance.hometown.id)
    print(instance.list[4].key)
    print(instance.object.key.key)

Now the key, value pairs are attributes - objects.

output:

John Smith
New York
123
1
1

Paste JSON as Code

Supports TypeScript, Python, Go, Ruby, C#, Java, Swift, Rust, Kotlin, C++, Flow, Objective-C, JavaScript, Elm, and JSON Schema.

  • Interactively generate types and (de-)serialization code from JSON, JSON Schema, and TypeScript
  • Paste JSON/JSON Schema/TypeScript as code

enter image description here

quicktype infers types from sample JSON data, then outputs strongly typed models and serializers for working with that data in your desired programming language.

output:

# Generated by https://quicktype.io
#
# To change quicktype's target language, run command:
#
#   "Set quicktype target language"

from typing import List, Union


class Hometown:
    name: str
    id: int

    def __init__(self, name: str, id: int) -> None:
        self.name = name
        self.id = id


class Key:
    key: int

    def __init__(self, key: int) -> None:
        self.key = key


class Object:
    key: Key

    def __init__(self, key: Key) -> None:
        self.key = key


class FbData:
    name: str
    hometown: Hometown
    list: List[Union[Key, int, str]]
    object: Object

    def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None:
        self.name = name
        self.hometown = hometown
        self.list = list
        self.object = object

This extension is available for free in the Visual Studio Code Marketplace.

Milovan Tomašević
  • 1,206
  • 1
  • 7
  • 13
  • 1
    Just saw that you can even use it online: [quicktype.io app](https://app.quicktype.io) – Night Train Mar 10 '21 at 08:42
  • For single use, I guess an online solution can help. For automation of the process, ie for repeating the steps, the online solution is not usable. In that example, the written solution would be adapted to the needs in order to successfully solve the problem. – Milovan Tomašević Mar 10 '21 at 09:14
-4

Use the json module (new in Python 2.6) or the simplejson module which is almost always installed.

Chris Morgan
  • 73,264
  • 19
  • 188
  • 199