Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Fork of mbed-sdk-tools by
Diff: utils.py
- Revision:
- 7:5af61d55adbe
- Parent:
- 0:66f3b5499f7f
- Child:
- 13:ab47a20b66f0
diff -r 744106007ff3 -r 5af61d55adbe utils.py --- a/utils.py Sat May 21 20:17:44 2016 +0100 +++ b/utils.py Tue Jun 07 11:21:44 2016 +0100 @@ -21,7 +21,8 @@ from shutil import copyfile from os.path import isdir, join, exists, split, relpath, splitext from subprocess import Popen, PIPE, STDOUT, call - +import json +from collections import OrderedDict def cmd(l, check=True, verbose=False, shell=False, cwd=None): text = l if shell else ' '.join(l) @@ -174,3 +175,23 @@ return False else: return True + +# Utility function: traverse a dictionary and change all the strings in the dictionary to +# ASCII from Unicode. Useful when reading ASCII JSON data, because the JSON decoder always +# returns Unicode string. +# Based on http://stackoverflow.com/a/13105359 +def dict_to_ascii(input): + if isinstance(input, dict): + return OrderedDict([(dict_to_ascii(key), dict_to_ascii(value)) for key, value in input.iteritems()]) + elif isinstance(input, list): + return [dict_to_ascii(element) for element in input] + elif isinstance(input, unicode): + return input.encode('ascii') + else: + return input + +# Read a JSON file and return its Python representation, transforming all the strings from Unicode +# to ASCII. The order of keys in the JSON file is preserved. +def json_file_to_dict(fname): + with open(fname, "rt") as f: + return dict_to_ascii(json.load(f, object_pairs_hook=OrderedDict))