Home > database >  Variable name as class name in python json
Variable name as class name in python json

Time:08-18

I have this piece of code

import json

class Object:
    def toJSON(self):
        return json.dumps(self, default=lambda o: o.__dict__,
                          sort_keys=False, indent=4)

languages={"pl_PL":"1","en_US":"2","de_DE":"4","fr_FR":"10","cs_CZ":"6"}
def generateJSON():
    product=Object()

    for lang in languages.keys():
        product.translations = Object()
        product.translations.lang=Object()
        product.translations.lang.name = "xxx"

    print(product.toJSON())

if __name__ == '__main__':
    generateJSON()

Which gives me an output:

{ "translations": { "lang": { "name": "xxx" } } }

How can I assing lang value to my Object name to get the output:

{ "translations": { "pl_PL": { "name": "xxx" }, { "en_US": { "name": "xxx" } }etc... }

CodePudding user response:

To use the string names in lang each time round the loop you need to use setattr() and getattr():

import json

class Object:
    def toJSON(self):
        return json.dumps(self, default=lambda o: o.__dict__,
                          sort_keys=False, indent=4)

languages={"pl_PL":"1","en_US":"2","de_DE":"4","fr_FR":"10","cs_CZ":"6"}
def generateJSON():
    product=Object()
    product.translations = Object()

    for lang in languages.keys():
        setattr(product.translations,lang,Object())
        getattr(product.translations,lang).name = "xxx"

    print(product.toJSON())

if __name__ == '__main__':
    generateJSON()

Output as requested.

  • Related