如何将 Excel 转换为 JSON 并将其附加到现有的 JSON 文件?

Posted

技术标签:

【中文标题】如何将 Excel 转换为 JSON 并将其附加到现有的 JSON 文件?【英文标题】:How to convert Excel to JSON and append it to existing JSON file? 【发布时间】:2022-01-21 02:49:10 【问题描述】:

我有这样的 Excel 文件:

-------------------------
| myValue | myValue2 | myValue3 |
--------+-------+--------
|   1   |   A   |   AA|
|   2   |   B   |   BB|
|   4   |   C   |   CC  |
|   5   |   D   |   DD  |
|   6   |   E   |   EE|
|   7   |   F   |   FF  |
|   8   |   G   |   GG  |
--------------------------

我想将我的 Excel 文件转换为 JSON 格式


"myValue":

"1":"1",
"2":"2"
,
"myValue2":

"A":"A",
"B":"B"
,
"myValue3":

"AA":"AA",
"BB":"BB"


我已经有一个这样的 JSON 文件,所以我应该将值从 Excel 附加到该文件。 它应该在“myValue”下添加值添加到该文件中“myValue”下的另一个 JSON 文件。我已经从网站上尝试了一些解决方案,但它们对我不起作用。 此外,问题在于 myValue、myValue2、myValue3 并不总是与此处显示的顺序相同。 理想的解决方案是在已经包含它的 JSON 文件中找到 myValue,并直接从包含相同值的 Excel 行中添加值。

【问题讨论】:

请添加示例excel数据 @abdulsaboor,添加。 :) 如果您愿意使用 pandas 加载 Excel 文件,您可能会有一些运气:pandas.pydata.org/docs/reference/api/… 如果你不需要转换结果字典还有这个:pandas.pydata.org/docs/reference/api/… @SimonCrowe,您能否添加一些示例代码或示例,因为我是 Python 新手? 【参考方案1】:

这行得通

# Importing dependencies 
import pandas
import json

# Reading xlsx into pandas dataframe
df = pandas.read_excel('../Data/18-12-21.xlsx')

# Encoding/decoding a Dataframe using 'columns' formatted JSON
jsonfile = df.to_json(orient='columns')

# Print out the result
print('Excel Sheet to JSON:\n', jsonfile)

# Make the string into a list to be able to input in to a JSON-file
json_dict = json.loads(jsonfile)

# write from and file to write to
with open('data.json', 'w') as json_file:
    json.dump(json_dict, json_file)

输出


    "myValue": 
        "0": 1,
        "1": 2,
        "2": 4,
        "3": 5,
        "4": 6,
        "5": 7,
        "6": 8
    ,
    "myValue2": 
        "0": "A",
        "1": "B",
        "2": "C",
        "3": "D",
        "4": "E",
        "5": "F",
        "6": "G"
    ,
    "myValue3": 
        "0": "AA",
        "1": "BB",
        "2": "CC",
        "3": "DD",
        "4": "EE",
        "5": "FF",
        "6": "GG"
    

【讨论】:

即使 excel 中的行值顺序不同,这是否有效?例如,一次是如图所示,另一次是myValue2,myValue3,myValue。 会的,但这当然也会改变您收到的 JSON 输出。 好的,但是它会影响将它添加到另一个 JSON 文件吗?因为它应该在另一个文件中找到 myValue 并从生成的文件中添加值? 有没有办法将键从“0”等更改为与值相同? 不,它不会影响它,因为我使用了 orient="columns" 编码附加其他文件将始终首先识别列标题。

以上是关于如何将 Excel 转换为 JSON 并将其附加到现有的 JSON 文件?的主要内容,如果未能解决你的问题,请参考以下文章