找不到关于 json.tool 的文档

Mat*_*art 13 python json

我可以在网上找到零星的文章,它们使用 json.tool 生成漂亮的 Python,但没有明确的使用文档。我检查了docs.python。但是没有 json.tool 的正式文档。

我有几个工作流(由其他人编写)使用 json.tool 来验证 json,但我也看到警告 json.tool 并不总是生成有效 json 的帖子。所以我想更多地了解 json.tool 是如何工作的。

任何人都可以推荐有关 json.tool 的清晰、全面的文档吗?

Ant*_*hon 22

如果您查看 python JSON 库的正式文档,您会发现调用json.tool应该是python -mjson.tool. 这表示你的python安装目录tool.py下的文件中的程序json,或者你的python安装目录下的文件__init__.py中的程序。tooljson

该文件实际上是两者中的前者,其main()功能是< 20行代码,可以很容易地分析:

  • 如果没有参数,则它用作管道:JSON in 和 JSON out
  • 如果有一个参数作为 JSON 输入文件,则输出到 stdout
  • 有两个参数,第一个是 JSON 输入文件,第二个是 JSON 输出文件

如果您提供更多参数,它将实际显示用法:

$ python -m json.tool a b c
/opt/python/2.7.11/lib/python2.7/json/tool.py [infile [outfile]]
Run Code Online (Sandbox Code Playgroud)

那是针对 2.7 版本的工具。3.5.1 版本有一个额外的参数,如果您使用,则会显示这些参数-h

$ python -m json.tool -h

usage: python -m json.tool [-h] [--sort-keys] [infile] [outfile]

A simple command line interface for json module to validate and pretty-print
JSON objects.

positional arguments:
  infile       a JSON file to be validated or pretty-printed
  outfile      write the output of infile to outfile

optional arguments:
  -h, --help   show this help message and exit
  --sort-keys  sort the output of dictionaries alphabetically by key
Run Code Online (Sandbox Code Playgroud)