简体   繁体   中英

Unable to create a formatted JSON file in python

I am a newbie in python (Using python 2.7) and I am trying to write a JSON file like this

import os;
import json;

BUILDNUMBER = "1.0.0"

class Foo(object):
    def __init__(self):
       self.buildNumber = BUILDNUMBER;

foo = Foo()
s = json.dumps(foo.__dict__) 
os.system("echo {0} > ./build.json".format(s));

The contents of build.json looks like this

{buildNumber: 1.0.0}

I want it to look like this

{"buildNumber" : "1.0.0"}

Any help is appreciated.

No, you do not use os.system to call echo to redirect to a file. Never. In Python. Like ever.

Since no one showed how to do it right, this is how you write a JSON file in Python:

with open('./build.json', 'w') as f:
    json.dump(foo.__dict__, f) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM