Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing a Python namedtuple to json

What is the recommended way of serializing a namedtuple to json with the field names retained?

Serializing a namedtuple to json results in only the values being serialized and the field names being lost in translation. I would like the fields also to be retained when json-ized and hence did the following:

class foobar(namedtuple('f', 'foo, bar')):     __slots__ = ()     def __iter__(self):         yield self._asdict() 

The above serializes to json as I expect and behaves as namedtuple in other places I use (attribute access etc.,) except with a non-tuple like results while iterating it (which fine for my use case).

What is the "correct way" of converting to json with the field names retained?

like image 632
calvinkrishy Avatar asked May 06 '11 04:05

calvinkrishy


People also ask

What is JSON serialization and deserialization in Python?

It is a format that encodes the data in string format. JSON is language independent and because of that, it is used for storing or transferring data in files. The conversion of data from JSON object string is known as Serialization and its opposite string JSON object is known as Deserialization.

When should I use Namedtuple?

In general, you can use namedtuple instances wherever you need a tuple-like object. Named tuples have the advantage that they provide a way to access their values using field names and the dot notation. This will make your code more Pythonic.

Is Namedtuple immutable?

A Python namedtuple is Immutable Like its regular counterpart, a python namedtuple is immutable. We can't change its attributes. To prove this, we'll try changing one of the attributes of a tuple of type 'Colors'.


1 Answers

If it's just one namedtuple you're looking to serialize, using its _asdict() method will work (with Python >= 2.7)

>>> from collections import namedtuple >>> import json >>> FB = namedtuple("FB", ("foo", "bar")) >>> fb = FB(123, 456) >>> json.dumps(fb._asdict()) '{"foo": 123, "bar": 456}' 
like image 76
benselme Avatar answered Sep 18 '22 23:09

benselme