SoFunction
Updated on 2024-12-10

Python implementation of complex objects to JSON method examples

In this article, examples of Python implementation of complex objects to JSON. Shared for your reference, as follows:

In Python for simple object to json is still relatively simple, as follows:

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

For complex objects, you can use the following methods to achieve this, for example:

import json
class Customer:
  def __init__(self, name, grade, age, home, office):
     = name
     = grade
     = age
     = Address(home, office)
  def __repr__(self):
    return repr((, , , , ))
class Address:
  def __init__(self, home, office):
     = home
     = office
  def __repr__(self):
    return repr((, , ))
customers = [
    Customer('john', 'A', 15, '111', 'aaa'),
    Customer('jane', 'B', 12, '222', 'bbb'),
    Customer('dave', 'B', 10, '333', 'ccc'),
    ]
json_str = (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 again for you to recommend a few more practical json online tools for your reference:

on-lineJSONCode checking, inspection, beautification and formatting tools:
http://tools./code/json

JSONOnline formatting tool:
http://tools./code/jsonformat

Online XML/JSONInterconversion tool:
http://tools./code/xmljson

jsonCode online formatting/beautification/compression/editing/conversion tool:
http://tools./code/jsoncodeformat

on-linejsonCompression/Transparency Tool:
http://tools./code/json_yasuo_trans

For more Python related content, readers can check out this site's topic:Python manipulation json skills summary》、《Summary of Python coding manipulation techniques》、《Summary of Python image manipulation techniques》、《Python Data Structures and Algorithms Tutorial》、《Python Socket Programming Tips Summary》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniques》、《Python introductory and advanced classic tutorialsand theSummary of Python file and directory manipulation techniques

I hope that the description of this article will help you in Python programming.