JSON usage in Python

情到浓时终转凉″ 提交于 2019-12-08 05:26:56

问题


I'm looking through the json documentation and I'm trying to understand how to actually convert a Python object into JSON data, and then convert that data back into a Python object. I understand you can pass lists, dicts, and tuples of "primitives" like in the example at the top, but I tried creating a very minimal object and passing it to json.dumps() and got "object is not JSON serializable".

What is the proper way to make an object JSON serializable? I'm currently imagining writing a method which converts my object into a dictionary then passes it to json.dump() and a parallel method to take the dictionary and construct a new object from it. However that seems really redundant and limited, so I feel like there must be something I'm missing. Can anyone help fill me in?


回答1:


Take a look at load() and dump(); each accept an object_hook function to decode and encode objects not ordinarily JSONable. Maybe this will do for you.




回答2:


The following snipped of code illustrates several aspects of working with JSON in Python 3. Take note of the JSONEncoder class and the implementation of encoding decimal and datetime.

import json
from decimal import Decimal
from datetime import datetime, date

class JSONEncoder(json.JSONEncoder):
  def default(self, o):
    if isinstance(o, Decimal):
      return float(o)
    elif isinstance(o, (datetime, date)):
      return o.isoformat()
    return super().default(self,o)

class JSONDecoder(json.JSONDecoder):
  pass

_Default_Encoder = JSONEncoder(
  skipkeys=False,
  ensure_ascii=False,
  check_circular=True,
  allow_nan=True,
  indent=None,
  separators=None,
  default=None,
  )

_Default_Decoder = JSONDecoder(
  object_hook=None, 
  object_pairs_hook=None
  )

Encode = _Default_Encoder.encode
Decode = _Default_Decoder.decode


来源:https://stackoverflow.com/questions/4882189/json-usage-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!