Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Variable name as class name in python json

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"
}
} }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading