How we can convert python Object to JSON data and JSON Data to python Object:

How we can convert python Object to JSON data and JSON Data to python Object:

Many times we need to set different values in the same attribute in JSON for testing point of view. in this case we have to manage the number of JSON files for different values of the same attribute.

In these scenarios, we can simply create a python object for specific JSON data then we can set different values of the key as per our business scenario.

Example:

import json
from collections import namedtuple
from json import JSONEncoder


class Pet:
    def __init__(self, id, category, name, photoUrls, tags, status):
        self.id, self.category, self.name, self.photoUrls, self.tags, self.status = id, category, name, photoUrls, tags, status


class category:
    def __init__(self, id, name):
        self.id, self.name = id, name


class PetEncoder(JSONEncoder):
    def default(self, o):
        return o.__dict__


def CustompetDecoder(petDict):
    return namedtuple('X', petDict.keys())(*petDict.values())


# encoding the python object into the json format
cate = category(12345, 'Shiv Kushwaha')
cate1 = category(12345, 'Vanit Kushwaha')
photourls = ["this is url1", "this is url2"]
tags = [cate, cate1]
pets = Pet(123456, cate, "GP kushwaha", photourls, tags, "available")
petdata = json.dumps(pets, indent=4, cls=PetEncoder)
#print(petdata)
# decoding json into the object (convert json to python object)
petObject = json.loads(petdata, object_hook=CustompetDecoder)
#print(petObject)
print(petObject.tags[0].id)        

#pytest#python #restAPItesting



To view or add a comment, sign in

Others also viewed

Explore topics