[PATCH] D68223: [LNT] Python 3 support: fix convert to JSON

Thomas Preud'homme via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Mon Sep 30 06:56:52 PDT 2019


thopre created this revision.
thopre added reviewers: cmatthews, hubert.reinterpretcast, kristof.beyls.

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.


https://reviews.llvm.org/D68223

Files:
  lnt/formats/JSONFormat.py


Index: lnt/formats/JSONFormat.py
===================================================================
--- lnt/formats/JSONFormat.py
+++ lnt/formats/JSONFormat.py
@@ -19,9 +19,17 @@
     return json.load(path_or_file)
 
 
+def _dump_format(obj, fp):
+    # The json module produces str objects but fp is opened in binary mode
+    # (since Plistlib only dump to binary mode files) so we first dump into
+    # a string a convert to UTF-8 before outputing.
+    json_str = json.dumps(obj)
+    fp.write(json_str.encode())
+
+
 format = {
     'name': 'json',
     'predicate': _matches_format,
     'read': _load_format,
-    'write': json.dump,
+    'write': _dump_format,
 }


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D68223.222419.patch
Type: text/x-patch
Size: 674 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20190930/625c319a/attachment.bin>


More information about the llvm-commits mailing list