0

I have class 'player' which has several int and string filds. How to encode it as JSON object?

Sejn
  • 63
  • 10
  • Can you please give some example code of the class you are using? – Lix Jul 19 '15 at 09:43
  • What you would need to do is map each of the classes properties to key:value pairs. – Lix Jul 19 '15 at 09:44
  • class Players: name = '' position = '' points = '' min = '' fgm_a = '' threePm_a = '' ftm_a = '' oreb = '' dreb = '' some filds are string and some int. – Sejn Jul 19 '15 at 09:45

2 Answers2

1

Pass in a default method to the JSON encoder:

import json


class Player(object):
    def __init__(self, name, number):
        self.name = name
        self.number = number


def encode_json(o):
    if isinstance(o, Player):
        return o.__dict__

        # or, alternatively ...
        return {
            'name': o.name,
            'number': o.number,
        }

    raise TypeError('Cannot serialize object of type %s' % type(o))

doc = {'team': [
    Player('Joe', 1),
]}
print(json.dumps(doc, default=encode_json))

In many cases, simply returning __dict__ will suffice. If you need additional information (say, the class name) or do not want to encode everything (maybe a Player object can hold a password you don't want to give out), simply define your own result as shown after # or, alternatively.

phihag
  • 278,196
  • 72
  • 453
  • 469
  • it is working, thx! Can u just explain to me how this parametar 'default = encode_json' working without passing his object parametar? – Sejn Jul 19 '15 at 11:42
  • @Sejn `encode_json` is a function. In Python, functions are objects like any other. Instead of actually calling the function as `encode_json(something)` would do, we let the `json.dumps` method call the function with the parameters it deems fit. – phihag Jul 19 '15 at 11:49
  • I get it. But i still dont get how this function encode_json works. End this o, is that some special object or what? – Sejn Jul 19 '15 at 12:21
  • `json.dumps` can only handle `str`, `int`, `tuple`, `list`, and `dict`. `json.dumps` calls the passed function when cannot handle an object. The only argument to the function is the object that `json.dumps` has been asked to encode. This passed function (here called `encode_json`) can then either return an object that `json.dumps` *can* handle, or throw a `TypeError`. – phihag Jul 19 '15 at 12:28
0

If all the members of the object should be converted (i.e. you don't have extra members used for optimizations like cached values) then you can just use

json.dumps(obj.__dict__)

for the loader may be it's better to add also a member containing the class name if this is not implied by the context...

d = obj.__dict__.copy()
d['classname'] = obj.__class__.__name__
return json.dumps(s)

If the object however also contains references to other objects then you must decide first a schema to use when passing these releations (e.g. serializing those members to JSON using an object ID value). Using recursive serialization may be acceptable if your data structure is just a tree and not a general graph of references.

6502
  • 112,025
  • 15
  • 165
  • 265