【问题标题】:How to generate a treeview Json from a List or Dataframe in Python?如何从 Python 中的列表或数据框生成树视图 Json?
【发布时间】:2023-01-13 14:58:07
【问题描述】:

我有以下列表/数据框:

[['title1','title1_chapter1','title1_chapter1_section1','title1_chapter1_href1'], ['title1','title1_chapter1','title1_chapter1_section2','title1_chapter1_href2'], ['title1','title1_chapter2','title1_chapter2_section1','title1_chapter2_href1'], ['title1','title1_chapter2','title1_chapter2_section2','title1_chapter2_href2'], ['title2','title2_chapter1','title2_chapter1_section1','title2_chapter1_href1']]

我想将它转换为以下嵌套的 Json,以便它可以在 bootstrap treeview 中使用。

[
  {
    "nodes": [
      {
        "nodes": [
          {
            "text": "title1_chapter1_section1",
            "href": "title1_chapter1_href1"
          },{
            "text": "title1_chapter1_section2",
            "href": "title1_chapter1_href2"
          }],
        "text": "title1_chapter1"
      },{
        "nodes": [
          {
            "text": "title1_chapter2_Section1",
            "href": "title1_chapter2_href1"
          },{
            "text": "title1_chapter2_section2",
            "href": "title1_chapter2_href2"
          }],
        "text": "title1_chapter2"
      }],
    "text": "title1"
  },{
    "nodes": [
      {
        "nodes": [
          {
            "text": "title2_chapter1_section1",
            "href": "title2_chapter1_href2"
          }],
        "text": "title2_chapter1"
      }],
    "text": "title2"
  }
]

那么,如何在 Python 中实现呢?提前致谢。

【问题讨论】:

    标签: python json dataframe nested treeview


    【解决方案1】:

    将 DataFrame 转换为 JSON 你可以在这个 Documentation 中看到
    这是文档中的示例

    import json
    df = pd.DataFrame(
        [["a", "b"], ["c", "d"]],
        index=["row 1", "row 2"],
        columns=["col 1", "col 2"],
    )
    result = df.to_json(orient="split")
    parsed = json.loads(result)
    json.dumps(parsed, indent=4)  
    

    结果:

    {
        "columns": [
            "col 1",
            "col 2"
        ],
        "index": [
            "row 1",
            "row 2"
        ],
        "data": [
            [
                "a",
                "b"
            ],
            [
                "c",
                "d"
            ]
        ]
    }
    

    如果列表中的数据你可以做这样的事情

    import json
    
    aList = [{'a':1, 'b':2}, {'c':3, 'd':4}]
    jsonStr = json.dumps(aList, indent=4)
    print(jsonStr)
    

    结果:

    [
        {
            "a": 1,
            "b": 2
        },
        {
            "c": 3,
            "d": 4
        }
    ]
    

    我希望这个答案能帮助解决你的问题

    【讨论】:

      猜你喜欢
      • 2016-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-04
      • 2022-01-04
      • 1970-01-01
      相关资源
      最近更新 更多