What is deserialize and serialize in JSON?

前端 未结 3 1113
陌清茗
陌清茗 2020-11-29 15:25

I have seen the terms \"deserialize\" and \"serialize\" with JSON. What do they mean?

3条回答
  •  一个人的身影
    2020-11-29 15:43

    In the context of data storage, serialization (or serialisation) is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer) or transmitted (for example, across a network connection link) and reconstructed later. [...]
    The opposite operation, extracting a data structure from a series of bytes, is deserialization. From Wikipedia

    In Python "serialization" does nothing else than just converting the given data structure (e.g. a dict) into its valid JSON pendant (object).

    • Python's True will be converted to JSONs true and the dictionary itself will then be encapsulated in quotes.
    • You can easily spot the difference between a Python dictionary and JSON by their Boolean values:
      • Python: True / False,
      • JSON: true / false
    • Python builtin module json is the standard way to do serialization:

    Code example:

    data = {
        "president": {
            "name": "Zaphod Beeblebrox",
            "species": "Betelgeusian",
            "male": True,
        }
    }
    
    import json
    json_data = json.dumps(data, indent=2) # serialize
    restored_data = json.loads(json_data) # deserialize
    
    # serialized json_data now looks like:
    # {
    #   "president": {
    #     "name": "Zaphod Beeblebrox",
    #     "species": "Betelgeusian",
    #     "male": true
    #   }
    # }
    

    Source: realpython.com

提交回复
热议问题