<p>你要找的是<a href="https://docs.python.org/3/library/json.html#json.dump" rel="nofollow noreferrer">[Python 3]: json.<strong>dump</strong>(<em>obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw</em>)</a>的缩进:</p>
<blockquote>
<p>If <em>indent</em> is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or <code>""</code> will only insert newlines. <code>None</code> (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If <em>indent</em> is a string (such as <code>"\t"</code>), that string is used to indent each level.</p>
</blockquote>
<p><em>代码.py</em>:</p>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3
import sys
import json
def main(argv):
with open("in.json") as inf:
obj = json.load(inf)
print("Original date:", obj["myData"])
# Modify obj["myData"] to whatever you need (self.timeISO8601ZuluUTC())
output_indent = int(argv[0]) if len(argv) and argv[0].isdecimal() else None
with open("out.json", "w") as outf:
json.dump(obj, outf, indent=output_indent)
if __name__ == "__main__":
print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
main(sys.argv[1:])
print("Done.")
</code></pre>
<p><strong>输出</strong>:</p>
<blockquote>
<pre class="lang-bat prettyprint-override"><code>[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q055578224]> sopr.bat
*** Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ***
[prompt]> dir /b
code.py
in.json
[prompt]> type in.json
{
"server": "https://abc.us",
"name":"XYZ",
"myData":"2019-04-08T15:43:05.810483Z",
"someFlg":"T",
"moreData":"k"
}
[prompt]> "e:\Work\Dev\VEnvs\py_064_03.07.03_test0\Scripts\python.exe" code.py
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Original date: 2019-04-08T15:43:05.810483Z
Done.
[prompt]> dir /b
code.py
in.json
out.json
[prompt]> type out.json
{"server": "https://abc.us", "name": "XYZ", "myData": "2019-04-08T15:43:05.810483Z", "someFlg": "T", "moreData": "k"}
[prompt]>
[prompt]> "e:\Work\Dev\VEnvs\py_064_03.07.03_test0\Scripts\python.exe" code.py 2
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Original date: 2019-04-08T15:43:05.810483Z
Done.
[prompt]> dir /b
code.py
in.json
out.json
[prompt]> type out.json
{
"server": "https://abc.us",
"name": "XYZ",
"myData": "2019-04-08T15:43:05.810483Z",
"someFlg": "T",
"moreData": "k"
}
</code></pre>
</blockquote>
<p>如您所见,该文件已被很好地重写,而无需修改其原始(文本)内容。你知道吗</p>