Skip to content

Commit 398d797

Browse files
author
Thomas Preud'homme
committed
[LNT] Python 3 support: fix convert to JSON
Plistlib and json modules have conflicting requirements for their dump methods: Plistlib expects its file handle to be a writable binary file object while json expects it to be a writable text file object. This commit solves this issue by dumping the JSON into a temporary string which is encoded to UTF-8 (JSON format RFC 7159 requires UTF-8, UTF-16 or UTF-32 encoding and UTF-8 is the recommended default) before being output. This allows to keep delegating file opening to Click and avoid a refactoring to abstract the opening mode between supported formats. Reviewers: cmatthews, hubert.reinterpretcast, kristof.beyls Reviewed By: hubert.reinterpretcast Subscribers: llvm-commits Differential Revision: https://reviews.llvm.org/D68223 llvm-svn: 373615
1 parent adf6b12 commit 398d797

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

lnt/formats/JSONFormat.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,17 @@ def _load_format(path_or_file):
1919
return json.load(path_or_file)
2020

2121

22+
def _dump_format(obj, fp):
23+
# The json module produces str objects but fp is opened in binary mode
24+
# (since Plistlib only dump to binary mode files) so we first dump into
25+
# a string a convert to UTF-8 before outputing.
26+
json_str = json.dumps(obj)
27+
fp.write(json_str.encode())
28+
29+
2230
format = {
2331
'name': 'json',
2432
'predicate': _matches_format,
2533
'read': _load_format,
26-
'write': json.dump,
34+
'write': _dump_format,
2735
}

0 commit comments

Comments
 (0)