Construct YAML that contains JSON data in python -
i have file config.json contains json follows:
{ "json":{ "type":"service", "project":"project", "key":"key", "client":"client" }, "project_id":"1" } i want include json data in yaml file.
yaml (this required output):
contexts: - config: json: | { "type": "service", "project": "project", "key": "key", "client": "client" } project_id: "1" name: cloud current-context: cloud here, 2 keys json & project_id coming config.json data. json data added config under contexts.
the following underlines 2 information coming config.json data.
contexts: - config: json: | ---- { } project_id: "1" ---------- name: cloud current-context: cloud how can this?
i have tried below:
with open("config.json") f: config = yaml.safe_load(f) config_map = {} key in config: config_map[key] = str(config[key]) context = dict( config=config_map, name="cloud", ) data = { "contexts": [context], "current-context": "cloud", } but not correct.
can point me correct direction?
if want dump value key json literal block style scalar can use:
import sys ruamel import yaml open("config.json") f: config = yaml.safe_load(f) key in config: try: int(config[key]) val = yaml.scalarstring.doublequotedscalarstring(config[key]) except typeerror: val = yaml.round_trip_dump( config[key], default_flow_style=true, width=10, default_style='"') val = val.replace('{"', '{\n "').replace('"}', '"\n}') val = yaml.scalarstring.preservedscalarstring(val) config[key] = val context = dict( config=config, name="cloud", ) data = { "contexts": [context], "current-context": "cloud", } yaml.round_trip_dump(data, sys.stdout) which gives exactly required output. might want adjust try statement determines on gets rendered double quoted scalar, , literal block scalar.
Comments
Post a Comment