【问题标题】:Pretty JSON Formatting in IPython NotebookIPython Notebook 中漂亮的 JSON 格式
【发布时间】:2013-09-23 06:17:24
【问题描述】:

是否有现有方法可以让json.dumps() 输出在 ipython 笔记本中显示为“漂亮”格式的 JSON?

【问题讨论】:

    标签: python json ipython-notebook


    【解决方案1】:

    对于 Jupyter 笔记本,可能足以生成在新选项卡中打开的链接(使用 firefox 的 JSON 查看器):

    from IPython.display import Markdown
    def jsonviewer(d):
       f=open('file.json','w')
       json.dump(d,f)
       f.close()
       print('open in firefox new tab:')
       return Markdown('[file.json](./file.json)')
    
    jsonviewer('[{"A":1}]')
    'open in firefox new tab:
    

    file.json

    【讨论】:

      【解决方案2】:

      这可能与 OP 的要求略有不同,但您可以使用 IPython.display.JSON 以交互方式查看 JSON/dict 对象。

      from IPython.display import JSON
      JSON({'a': [1, 2, 3, 4,], 'b': {'inner1': 'helloworld', 'inner2': 'foobar'}})
      

      编辑:这适用于 Hydrogen 和 JupyterLab,但不适用于 Jupyter Notebook 或 IPython 终端。

      内部Hydrogen

      【讨论】:

      • 我从未如此快乐!
      • 让我感到困惑的是,这在 Jupyter Lab 中有效,但不适用于旧笔记本。如果存在,它会在那里调用 repr_json
      【解决方案3】:

      我只是将扩展变量添加到@Kyle Barron 答案:

      from IPython.display import JSON
      JSON(json_object, expanded=True)
      

      【讨论】:

      • 它对我不起作用TypeError: __init__() got an unexpected keyword argument 'expanded'
      • 这对我很有效。使用“扩展”关键字时没有错误。我的 IPython.__version__ 显示“7.8.0”。
      • 对我来说没有错误,但我得到的只是输出<IPython.core.display.JSON object>。没有交互式漂亮打印。
      【解决方案4】:
      import uuid
      from IPython.display import display_javascript, display_html, display
      import json
      
      class RenderJSON(object):
          def __init__(self, json_data):
              if isinstance(json_data, dict):
                  self.json_str = json.dumps(json_data)
              else:
                  self.json_str = json_data
              self.uuid = str(uuid.uuid4())
      
          def _ipython_display_(self):
              display_html('<div id="{}" style="height: 600px; width:100%;"></div>'.format(self.uuid), raw=True)
              display_javascript("""
              require(["https://rawgit.com/caldwell/renderjson/master/renderjson.js"], function() {
              document.getElementById('%s').appendChild(renderjson(%s))
              });
              """ % (self.uuid, self.json_str), raw=True)
      

      以可折叠格式输出您的数据:

      RenderJSON(your_json)
      

      从这里复制粘贴:https://www.reddit.com/r/IPython/comments/34t4m7/lpt_print_json_in_collapsible_format_in_ipython/

      Github:https://github.com/caldwell/renderjson

      【讨论】:

      • 我无法让它在 Jupyter 1.0 上运行。知道为什么吗? Javascript 控制台说:“SyntaxError: Unexpected token
      • 代码有问题。第 10 行应更改为 self.json_str = json_data。它解决了@user474491 报告的问题。
      • @Hassan:已修复!感谢您的建议。
      • 我已经更新了一些问题并让它在最新的 Jupyter Notebook 中工作,包括 @user474491 和 @Hassan 的建议,我还在__init__() 以确保我们可以安全地交错调用 python 的本机 print()RenderJSON() 并且仍然让它工作 gist.github.com/t27/48b3ac73a1479914f9fe9383e5d45325
      • 如果接受list类型会更好,因为caldwell/renderjson完全可以渲染json数组
      【解决方案5】:

      我发现此页面正在寻找一种方法来消除输出中的文字 \ns。我们正在使用 Jupyter 进行编码面试,我想要一种方法来显示函数 real perty like 的结果。我的 Jupyter (4.1.0) 版本不会将它们呈现为实际的换行符。我提出的解决方案是(我有点希望这不是最好的方法,但是......)

      import json
      
      output = json.dumps(obj, indent=2)
      
      line_list = output.split("\n")  # Sort of line replacing "\n" with a new line
      
      # Now that our obj is a list of strings leverage print's automatic newline
      for line in line_list:
          print line
      

      我希望这对某人有帮助!

      【讨论】:

        【解决方案6】:

        json.dumps 有一个indent 参数,打印结果就足够了:

        print(json.dumps(obj, indent=2))
        

        【讨论】:

        • 输出中的颜色怎么样?
        • 但是汉字在这种方法中与Unicode混淆了
        • 这根本不是真的。 Python 的 json.dumps 默认为 ensure_ascii=True 转义中文(或实际上:任何非 ASCII)代码点。使用print(json.dumps(obj, indent=2, ensure_ascii=False)),您将不会转义它们。
        猜你喜欢
        • 1970-01-01
        • 2014-01-25
        • 1970-01-01
        • 1970-01-01
        • 2023-03-31
        • 1970-01-01
        • 1970-01-01
        • 2018-12-29
        相关资源
        最近更新 更多