Created
July 24, 2016 09:29
-
-
Save EvgeneOskin/d4f349832e900ebea39874dbbf792f6a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import os.path | |
import json | |
import yaml | |
import argparse | |
def json_load_byteified(file_handle): | |
return _byteify( | |
json.load(file_handle, object_hook=_byteify), | |
ignore_dicts=True | |
) | |
def json_loads_byteified(json_text): | |
return _byteify( | |
json.loads(json_text, object_hook=_byteify), | |
ignore_dicts=True | |
) | |
def _byteify(data, ignore_dicts = False): | |
if isinstance(data, unicode): | |
return data.encode('utf-8') | |
if isinstance(data, list): | |
return [ _byteify(item, ignore_dicts=True) for item in data ] | |
if isinstance(data, dict) and not ignore_dicts: | |
return { | |
_byteify(key, ignore_dicts=True): _byteify(value, ignore_dicts=True) | |
for key, value in data.iteritems() | |
} | |
return data | |
def main(): | |
parser = argparse.ArgumentParser(description='convert json file to yaml') | |
parser.add_argument('path', metavar='PATH', help='Path to file.') | |
args = parser.parse_args() | |
json_path = args.path | |
yaml_path = os.path.splitext(json_path)[0] + '.yml' | |
with open(json_path) as json_file: | |
obj = json_load_byteified(json_file) | |
with open(yaml_path, 'w') as yaml_file: | |
yaml.dump(obj, stream=yaml_file) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment