Example of Python's method for implementing complex objects to JSON

  • 2020-06-03 07:18:59
  • OfStack

This article illustrates Python's method of converting complex objects to JSON. To share for your reference, specific as follows:

In Python, it is relatively simple to rotate json for simple objects, as follows:


import json
d = {'a': 'aaa', 'b': ['b1', 'b2', 'b3'], 'c': 100}
json_str = json.dumps(d)
print json_str

For complex objects, the following methods can be used, such as:


import json
class Customer:
  def __init__(self, name, grade, age, home, office):
    self.name = name
    self.grade = grade
    self.age = age
    self.address = Address(home, office)
  def __repr__(self):
    return repr((self.name, self.grade, self.age, self.address.home, self.address.office))
class Address:
  def __init__(self, home, office):
    self.home = home
    self.office = office
  def __repr__(self):
    return repr((self.name, self.grade, self.age))
customers = [
    Customer('john', 'A', 15, '111', 'aaa'),
    Customer('jane', 'B', 12, '222', 'bbb'),
    Customer('dave', 'B', 10, '333', 'ccc'),
    ]
json_str = json.dumps(customers, default=lambda o: o.__dict__, sort_keys=True, indent=4)
print json_str

The results are as follows


[
  {
    "address": {
      "home": "111",
      "office": "aaa"
    },
    "age": 15,
    "grade": "A",
    "name": "john"
  },
  {
    "address": {
      "home": "222",
      "office": "bbb"
    },
    "age": 12,
    "grade": "B",
    "name": "jane"
  },
  {
    "address": {
      "home": "333",
      "office": "ccc"
    },
    "age": 10,
    "grade": "B",
    "name": "dave"
  }
]

PS: About json operation, here are some more practical json online tools for your reference:

Online JSON code inspection, inspection, beautification, formatting tools:
http://tools.ofstack.com/code/json

JSON Online formatting tools:
http://tools.ofstack.com/code/jsonformat

Online XML/JSON interconversion tool:
http://tools.ofstack.com/code/xmljson

json code online formatting/beautification/compression/editing/conversion tools:
http://tools.ofstack.com/code/jsoncodeformat

Online json compression/escape tool:
http://tools.ofstack.com/code/json_yasuo_trans

More Python related content interested readers to view this site project: Python json operation skills summary, Python coding skills summary, Python pictures skills summary, "Python data structure and algorithm tutorial", "Python Socket programming skills summary", "Python function using techniques", "Python string skills summary", "Python introduction and advanced tutorial" and "Python file and directory skills summary"

I hope this article has been helpful in Python programming.


Related articles: