Skip to content

Commit 974d54f

Browse files
committed
Add support for preserving Unicode characters in jsonpatch CLI
If the JSON content contains some Unicode characters, the jsonpatch final output will encode the Unicode character using ASCII (i.e `\u0394`). This behaviour comes from the module `json.dump()` governed by a flag `ensure_ascii`[1]. For example: ```json /* patch.json */ [{ "op": "add", "path": "/SomeUnicodeSamples", "value": "𝒞𝘋𝙴𝓕ĢȞỈ𝕵 đ áê 🤩 äÄöÖüÜß" }] ``` After applying the patch on an empty source file `{}`, this is the output: ```json {"SomeUnicodeSamples": "\ud835\udc9e\ud835\ude0b...\u00fc\u00dc\u00df"} ``` This commit adds a flag `-u|--preserve-unicode` in the jsonpatch CLI to configure the behaviour of `json.dump`'s `ensure_ascii` flag. Using the `--preserve-unicode` flag, the cli will print the Unicode characters as-is without any encoding. [1]: https://docs.python.org/3/library/json.html#basic-usage
1 parent dbea3db commit 974d54f

File tree

2 files changed

+10
-7
lines changed

2 files changed

+10
-7
lines changed

bin/jsonpatch

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,8 @@ parser.add_argument('-i', '--in-place', action='store_true',
2424
help='Modify ORIGINAL in-place instead of to stdout')
2525
parser.add_argument('-v', '--version', action='version',
2626
version='%(prog)s ' + jsonpatch.__version__)
27-
27+
parser.add_argument('-u', '--preserve-unicode', action='store_true',
28+
help='Output Unicode character as-is without using Code Point')
2829

2930
def main():
3031
try:
@@ -72,8 +73,8 @@ def patch_files():
7273

7374
# By this point we have some sort of file object we can write the
7475
# modified JSON to.
75-
76-
json.dump(result, fp, indent=args.indent)
76+
77+
json.dump(result, fp, indent=args.indent, ensure_ascii=not(args.preserve_unicode))
7778
fp.write('\n')
7879

7980
if args.in_place:

doc/commandline.rst

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -74,10 +74,12 @@ The program ``jsonpatch`` is used to apply JSON patches on JSON files. ::
7474
PATCH Patch file
7575
7676
optional arguments:
77-
-h, --help show this help message and exit
78-
--indent INDENT Indent output by n spaces
79-
-v, --version show program's version number and exit
80-
77+
-h, --help show this help message and exit
78+
--indent INDENT Indent output by n spaces
79+
-b, --backup Back up ORIGINAL if modifying in-place
80+
-i, --in-place Modify ORIGINAL in-place instead of to stdout
81+
-v, --version show program's version number and exit
82+
-u, --preserve-unicode Output Unicode character as-is without using Code Point
8183
8284
Example
8385
^^^^^^^

0 commit comments

Comments
 (0)