且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django将JSON导入/重新格式化为模型

更新时间:2022-11-03 09:47:10

我编写了一个简单的脚本来解析输入文件并生成固定装置:

I wrote a simple script to parse the input file and generate a fixture:

import json
import copy

with open('/tmp/data.json') as dataf, open('/tmp/output.json', 'w') as out:
    data = json.load(dataf)
    newdata = []
    for i, block in enumerate(data):
        new = dict(model="appname.Item", pk=block['id'])
        new['fields'] = dict(item_name=block['item']['item_type']['name'],
                             timestamp=block['timestamp'],
                             value01=block['itemdatavalues'][0]['value'],
                             value02=block['itemdatavalues'][1]['value'])
        newdata.append(copy.deepcopy(new))
    json.dump(newdata, out, indent=2)

使用您的输入,结果是:

Using your input, this results in:

[
  {
    "pk": 1,
    "model": "appname.Item",
    "fields": {
      "item_name": "Item1",
      "timestamp": "2017-04-18 09:24:46",
      "value01": "15.00",
      "value02": "12.68"
    }
  },
  {
    "pk": 2,
    "model": "appname.Item",
    "fields": {
      "item_name": "Item1",
      "timestamp": "2017-04-18 09:25:44",
      "value01": "14.92",
      "value02": "12.42"
    }
  }
]

适合用作固定装置.显然,您必须修复appname.

Which is suitable for use as a fixture. Obviously, you will have to fix the appname.