【问题标题】:Trying to follow django docs to create serialized json尝试按照 django 文档创建序列化 json
【发布时间】:2021-12-08 16:14:47
【问题描述】:

尝试在 django 应用程序中播种数据库。我有一个转换为 json 的 csv 文件,现在我需要重新格式化它以匹配找到的 django 序列化所需格式here 这就是 django 可以接受的 json 格式(这看起来很像具有 3 个键的字典,第三个键的值本身就是字典):

[
    {
        "pk": "4b678b301dfd8a4e0dad910de3ae245b",
        "model": "sessions.session",
        "fields": {
            "expire_date": "2013-01-16T08:16:59.844Z",
            ...
        }
    }
]

我的 json 数据在使用 pandas 从 csv 转换后如下所示:

[{'model': 'homepage.territorymanager', 'pk': 1, 'Name': 'Aaron ##', 'Distributor': 'National Energy', 'State': 'BC', 'Brand': 'Trane', 'Cell': '778-###-####', 'email address': None, 'Notes': None, 'Unnamed: 9': None}, {'model': 'homepage.territorymanager', 'pk': 2, 'Name': 'Aaron Martin ', 'Distributor': 'Pierce ###', 'State': 'PA', 'Brand': 'Bryant/Carrier', 'Cell': '267-###-####', 'email address': None, 'Notes': None, 'Unnamed: 9': None},...]

我正在使用此功能尝试重新格式化

def re_serialize_reg_json(d, jsonFilePath):
    for i in d:
        d2 = {'Name': d[i]['Name'], 'Distributor' : d[i]['Distributor'], 'State' : d[i]['State'], 'Brand' : d[i]['Brand'], 'Cell' : d[i]['Cell'], 'EmailAddress' : d[i]['email address'], 'Notes' : d[i]['Notes']}
        d[i] = {'pk': d[i]['pk'],'model' : d[i]['model'], 'fields' : d2}
    print(d)

它返回这个没有任何意义的错误,因为 django 需要的格式有一个字典作为第三个键的值:

d2 = {'Name': d[i]['Name'], 'Distributor' : d[i]['Distributor'], 'State' : d[i]['State'], 'Brand' : d[i]['Brand'], 'Cell' : d[i]['Cell'], 'EmailAddress' : d[i]['email address'], 'Notes' : d[i]['Notes']}
TypeError: list indices must be integers or slices, not dict

任何帮助表示赞赏!

这是我为得到d所做的:

df = pandas.read_csv('/Users/justinbenfit/territorymanagerpython/territory managers - Sheet1.csv')
df.to_json('/Users/justinbenfit/territorymanagerpython/territorymanagers.json', orient='records')



jsonFilePath = '/Users/justinbenfit/territorymanagerpython/territorymanagers.json'

def load_file(file_path):
    with open(file_path) as f:
        d = json.load(f)
        return d
d = load_file(jsonFilePath)
print(d)

【问题讨论】:

  • d 是字典还是列表?遍历字典会得到字典的键,但遍历列表会得到该列表中的项目。

标签: python json django-fixtures


【解决方案1】:

D 实际上是一个包含多个字典的列表,因此为了使其正常工作,您需要将 for i in d 部分更改为:for i in range(len(d))

【讨论】:

  • 谢谢!我已经用我最初为获得 d 所做的工作更新了原始帖子。有没有办法将它创建为字典,这样我就可以避免使用列表?我假设首先使用字典会更好,但如果没关系,请告诉我。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-13
  • 1970-01-01
  • 2015-12-03
  • 1970-01-01
  • 2015-11-10
相关资源
最近更新 更多