Preserve Python tuples with JSON

前端 未结 5 790
Happy的楠姐
Happy的楠姐 2020-12-05 06:48

I\'m still a little new to this, so I might not know all the conventional terms for things:

Is it possible to preserve Python tuples when encoding with JSON? Right

5条回答
  •  误落风尘
    2020-12-05 07:14

    Nope, it's not possible. There is no concept of a tuple in the JSON format (see here for a concise breakdown of what types exist in JSON). Python's json module converts Python tuples to JSON lists because that's the closest thing in JSON to a tuple.

    You haven't given much detail of your use case here, but if you need to store string representations of data structures that include tuples, a few possibilities immediately come to mind, which may or may not be appropriate depending upon your situation:

    1. Create your own encoding and decoding functions
    2. Use pickle (careful; pickle.loads isn't safe to use on user-provided input).
    3. Use repr and ast.literal_eval instead of json.dumps and json.loads. repr will give you output reasonably similar in appearance to json.dumps, but repr will not convert tuples to lists. ast.literal_eval is a less powerful, more secure version of eval which will only decode strings, numbers, tuples, lists, dicts, booleans, and None.

    Option 3 is probably the easiest and simplest solution for you.

提交回复
热议问题