Home > database >  Python convert part of object to json
Python convert part of object to json

Time:12-15

I have a Python object that looks like:

import json

class ExampleObject():
    def __init__(self):
        super().__init__()
        self.tag = ''
        self.path = ''
        self.host = ''
        self.access = ''
        #self.uuid = ''
        self.attribute = ''

    def dump_to_json(self):
        return json.dumps(self.__dict__)

By using dump_to_json, I can convert the whole object to JSON, but I want to convert only some of these properties, for example, tag, path, host, to JSON, and ignore the rest.. Is there a simple way to pick and choose what object variables we can send to JSON?

Example code:

x = ExampleObject()
x.tag = '/tag/exampletagName'
x.path = '/prj/its/a/path/tag/exampletagName.fil'
x.host = 'server-host-name'
x.access = 'private'
jsonText = x.dump_to_json()

puts:

{"tag":"/tag/exampletagName", "path":"/prj/its/a/path/tag/exampletagName.fil", "host":"server-host-name","access":"private"}

and I want

{"tag":"/tag/exampletagName", "path":"/prj/its/a/path/tag/exampletagName.fil", "host":"server-host-name"}

Any suggestions?

CodePudding user response:

Maybe just add those fields to the dump which are needed.

def dump_to_json(self):
    return json.dumps({'tag': self.tag, 'path': self.path, 'host': self.host})
  • Related