简体   繁体   中英

How to convert Excel to JSON and append it to existing JSON file?

I have Excel file like this:

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

I want to convert my Excel file to JSON like

{
"myValue":
{
"1":"1",
"2":"2"
},
"myValue2":
{
"A":"A",
"B":"B"
},
"myValue3":
{
"AA":"AA",
"BB":"BB"
}
}

I already have a JSON file like this, so I should append values from Excel to that file. It should add values under "myValue" add to another JSON file under the "myValue" in that file. I already tried some solutions from site, but they did not work for me. Also, the problem is that myValue, myValue2, myValue3 are not always in the same order as displayed here . The ideal solution would be to find myValue in JSON file which already contains it and add values in it directly from Excel row which contains the same value.

This works

import pandas
import json

# Read excel document
df = pandas.read_excel('../Data/18-12-21.xlsx')

# 
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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM