【问题标题】:Dictionary to JSON in PythonPython中的字典到JSON
【发布时间】:2019-02-03 08:10:03
【问题描述】:

我正在尝试从 python 中的 excel 中读取输入,并将其转换为字典,例如:

import xlrd, json

d = {}
wb = xlrd.open_workbook('input.xlsx')
sh = wb.sheet_by_index(0)  
data=[]



for i in range(1,sh.nrows):
    d={}
    for j in range(sh.ncols):
        d[sh.cell(0,j).value] = sh.cell(i,j).value

    data.append(d)    
data

结果数据的格式为

[{'Age': 20.0, 'Brothers': 2.0, 'Name': 'Josh', 'Nationality': 'UK'},
 {'Age': 22.0, 'Brothers': 1.0, 'Name': 'Kim', 'Nationality': 'France'}]

我的“json”文件输出应该是这样的

{
'Children':[
{'Age': 20.0, 'Brothers': 2.0, 'Name': 'Josh', 'Nationality': 'UK'},
{'Age': 22.0, 'Brothers': 1.0, 'Name': 'Kim', 'Nationality': 'France'}
]
}

但是,当我调用 json.dumpts(data) 时,我会得到类似的东西

[
  {
    "Name": "Josh",
    "Age": 20.0,
    "Nationality": "UK",
    "Brothers": 2.0
  },
  {
    "Name": "Kim",
    "Age": 22.0,
    "Nationality": "France",
    "Brothers": 1.0
  }
]

所以有两个问题。如何在开头插入“儿童”字段,如何获得我想要的确切输出格式?谢谢

【问题讨论】:

  • json.dumps({'Children': data})?
  • json.dumps({'Children': data}, indent=2, sort_keys=True).
  • 我不工作。我已经试过了。还有其他建议吗?
  • “我不工作”到底是什么意思?输出不正确?抛出异常?
  • 没错。我想得到如上所示的确切输出。非常感谢。

标签: python json python-3.x dictionary


【解决方案1】:

试试:

import xlrd, json

d = {}
wb = xlrd.open_workbook('input.xlsx')
sh = wb.sheet_by_index(0)
data=[]

for i in range(1,sh.nrows):
    d={}
    for j in range(sh.ncols):
        d[sh.cell(0,j).value] = sh.cell(i,j).value

    data.append(d)
result={'Children':data}
print(json.dumps(result,indent=2))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-31
    • 2014-11-02
    • 2013-01-21
    • 2017-03-25
    • 2014-11-06
    • 1970-01-01
    • 2013-04-20
    • 2015-10-22
    相关资源
    最近更新 更多