【问题标题】:Excel to JSON conversionExcel 到 JSON 的转换
【发布时间】:2021-05-10 02:04:49
【问题描述】:

Thisexcel文件被转换为json, 但是在 python 中使用 pandas 库,它会明智地执行转换列,并显示为this。 我希望它以以下格式显示:

{"peopleInfo": [
{
  "Name": "John",
  "UserId": "39048",
  "FavoriteWords": [
    {
      "word": "Sincerity",
      "wordInfo": [
        {
          "meaning": "the quality or state of being sincere",
          "language": "English"
        },
        {
          "meaning": "honesty of mind",
          "language": "English"
        }, and so on....
      ]
    },
    {
      "word": "Sincerity",
      "wordInfo": [
        {
          "meaning": "the quality or state of being sincere",
          "language": "English"
        },
        {
          "meaning": "honesty of mind",
          "language": "English"
        }
      ]
    }, and so on....
  ]
},
{
  "Name": "Doe",
  "UserId": "23749",
  "FavoriteWords": [
    {
      "word": "Fun",
      "wordInfo": [
        {
          "meaning": "what provides amusement or enjoyment",
          "language": "English"
        },
        {
          "meaning": "a mood for find or making amusement",
          "language": "English"
        }
      ]
    },
    {
      "word": "Sharing",
      "wordInfo": [
        {
          "meaning": "to divide something between two or more people",
          "language": "English"
        },
        {
          "meaning": "joint use of a resource or space",
          "language": "English"
        }
      ]
    }
  ]
}, and so on....

] }

请不要考虑问题的上下文,我知道它很蹩脚,但我正在研究不同的东西。

【问题讨论】:

  • 如果没有一些自定义逻辑,您将无法获得嵌套的 json 格式。如果您不想为每一行输出一个包含一个对象的 json 数组,请执行 pandas.DataFrame.to_json(orient='records')

标签: python json excel pandas


【解决方案1】:

.csv 的结构可以在 python 中显示为字典。作为一个文件,您可以使用 nested .json 或 .xml 来实现这一点。

可以使用csv.DictReader 生成来自 .csv 的嵌套 .json,就像在 csv to nested JSON? 中一样

.json 是一种序列化格式,.csv 文件的结构是 嵌套的 .json、字典或 .xml 的结构。要使用 pandas 生成 .xml,请使用 .xml 处理模块,例如 xml.etree.ElementTree

https://stackabuse.com/reading-and-writing-xml-files-in-python-with-pandas/

另请参阅:How can I load a CSV file into a QTreeView?

How to transform an XML file using XSLT in Python?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-15
    • 2016-11-05
    • 1970-01-01
    • 2012-01-27
    • 2011-04-21
    • 2019-12-12
    • 2016-12-18
    • 1970-01-01
    相关资源
    最近更新 更多