【问题标题】:I need to create output from json that is pretty我需要从漂亮的 json 创建输出
【发布时间】:2019-07-01 15:35:57
【问题描述】:

我正在从活动目录中获取数据,并将其导出为 JSON。那太棒了。然后我可以通过 json.loads() 返回输出。

if output != '':
            return json.loads(output)

然后我得到丑陋的 json 输出,最终用户无法使用。我可以将其转换为 Python 字典,还是有其他模块可以在用户可接受的视图中显示数据?

我尝试用 Python json.decoder

转换 JSON

尝试 json.decode 时出现以下错误:

类型错误:是 不可 JSON 序列化

我已经尝试了这些建议,但它不起作用。迄今为止,以下代码是唯一有效的交互,没有可用的格式:

for server in ADDomainList:
    counter += 1
    psCommand = 'get-ADUser ' + cdsid + ' -Server ' + server + ' -Properties * | 
                 SELECT custom1,custom2,custom3,custom4 | ConvertTo-Json'

    proc = subprocess.Popen(['powershell.exe ', psCommand] 
           stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    output = proc.stdout.read().decode('utf-8')

    if output != '':
       return json.loads(output)
    if counter > 5:
           return 'AD Server Cannot Be Located'

我明白了:

“custom1”:“dummy1”,
"custom10": "dummy10",
"custom2": "dummy2",
"custom3": "dummy3",

我想退货:

字段名称1:数据1
字段名称10:Data10

没有引号,没有分隔符,只有事实......

【问题讨论】:

  • 如果您的 json 是 dict 对象(这是 loads 所做的),请使用 print(json.dumps(my_dict, indent=4))
  • 或者你可以使用漂亮的打印:https://docs.python.org/3.6/library/pprint.html
  • import pprint pprint.pprint(json)
  • 我已经尝试了这些建议,但它不起作用。迄今为止,以下代码是唯一有效的交互,并且没有可用的格式:

标签: python json dictionary output


【解决方案1】:

pprint 模块提供了“漂亮打印”任意 Python 数据结构的能力,该格式可用作解释器的输入。这是一个示例,说明如何使用它来漂亮地打印 JSON 对象。

import json
import pprint
from urllib.request import urlopen
with urlopen('http://pypi.python.org/pypi/configparser/json') as url:
    http_info = url.info()
    raw_data = url.read().decode(http_info.get_content_charset())
project_info = json.loads(raw_data)
result = {'headers': http_info.items(), 'body': project_info}
pprint.pprint(result)

输出:

{'body': {'info': {'_pypi_hidden': False,
                   '_pypi_ordering': 12,
                   'classifiers': ['Development Status :: 4 - Beta',
                                   'Intended Audience :: Developers',
                                   'License :: OSI Approved :: MIT License',
                                   'Natural Language :: English',
                                   'Operating System :: OS Independent',
                                   'Programming Language :: Python',
                                   'Programming Language :: Python :: 2',
                                   'Programming Language :: Python :: 2.6',
                                   'Programming Language :: Python :: 2.7',
                                   'Topic :: Software Development :: Libraries',
                                   'Topic :: Software Development :: Libraries :: Python Modules'],
                   'download_url': 'UNKNOWN',
                   'home_page': 'http://docs.python.org/py3k/library/configparser.html',
                   'keywords': 'configparser ini parsing conf cfg configuration file',
                   'license': 'MIT',
                   'name': 'configparser',
                   'package_url': 'http://pypi.python.org/pypi/configparser',
                   'platform': 'any',
                   'release_url': 'http://pypi.python.org/pypi/configparser/3.2.0r3',
                   'requires_python': None,
                   'stable_version': None,
                   'summary': 'This library brings the updated configparser from Python 3.2+ to Python 2.6-2.7.',
                   'version': '3.2.0r3'},
        'urls': [{'comment_text': '',
                  'downloads': 47,
                  'filename': 'configparser-3.2.0r3.tar.gz',
                  'has_sig': False,
                  'md5_digest': '8500fd87c61ac0de328fc996fce69b96',
                  'packagetype': 'sdist',
                  'python_version': 'source',
                  'size': 32281,
                  'upload_time': '2011-05-10T16:28:50',
                  'url': 'http://pypi.python.org/packages/source/c/configparser/configparser-3.2.0r3.tar.gz'}]},
'headers': [('Date', 'Sat, 14 May 2011 12:48:52 GMT'),
            ('Server', 'Apache/2.2.16 (Debian)'),
            ('Content-Disposition', 'inline'),
            ('Connection', 'close'),
            ('Transfer-Encoding', 'chunked'),
            ('Content-Type', 'application/json; charset="UTF-8"')]}

【讨论】:

  • 谢谢,我相信 pprint 是最好的选择。除此之外,我会将其发送到 Web 前端,使其用户友好。
【解决方案2】:

json 模块已经使用 indent 参数实现了一些基本的漂亮打印:

import json

json_ = '["foo", {"bar":["val1", "val2", "val3", "val4"]}]'
parsed = json.loads(json_)
print (json.dumps(parsed, indent=2, sort_keys=True))

输出:

[
  "foo",
  {
    "bar": [
      "val1",
      "val2",
      "val3",
      "val4"
    ]
  }
]

缩进:缩进的空格数(没有缩进,你只会得到一行)

【讨论】:

    猜你喜欢
    • 2013-02-09
    • 2014-12-13
    • 1970-01-01
    • 2015-09-05
    • 2012-05-18
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    • 2014-08-16
    相关资源
    最近更新 更多