Skip to content

Instantly share code, notes, and snippets.

@webghostx
Last active March 4, 2017 17:04
Show Gist options
  • Save webghostx/f2a7fc80e41b2f18f133213f6c55583d to your computer and use it in GitHub Desktop.
Save webghostx/f2a7fc80e41b2f18f133213f6c55583d to your computer and use it in GitHub Desktop.
Formatierte JSON Konfiguration in Python
from collections import OrderedDict # required for maintaining order data
import json
class AppConfig:
'''
sample config class
load and save readable
json configuration files
http://usysto.net/formatierte-json-konfiguration-python_846
'''
def __init__(self, configFile = False):
self.configFile = False
self.get = False
if configFile:
self.configFile = configFile
self.configLoad()
def configLoad(self):
try:
with open(self.configFile) as data:
obj = json.load(
data,
object_pairs_hook = OrderedDict # maintaining order data
)
self.get = obj
return True
except Exception:
return False
def configSave(self, obj = False):
obj = obj or self.get
try:
with open(self.configFile, "w") as outfile:
json.dump(
obj,
outfile,
ensure_ascii = False, # Keep special characters
indent = 4
)
return True
except Exception:
return False
''' content of *.json
{
"string": "ok",
"bool": true,
"object": {
"int": 3,
"float": 3.3
}
}
'''
'''
Application example
'''
AppConfig = AppConfig()
AppConfig.configFile = '/home/user/App/config.json' # absolute path to *.json
AppConfig.configLoad()
print AppConfig.get['string']
AppConfig.get['object']['int'] = 4
if AppConfig.configSave():
print 'New value has been saved'
#end
@webghostx
Copy link
Author

Weitere Informationen unter Formatierte JSON Konfiguration in Python

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment