在python中将数据序列化为JSON

时间:2014-04-04 14:59:10

标签: python json

有人可以给我一些如何将数据序列化到文件的指南,类似于下面的介绍吗?

{
  "minShift": -0.5,
  "maxShift": 0.5,
  "stepShift": 0.002,
  "feeds": {
    "CFH": "CFH_20140318T0900.txt",
    "LMAX": "LMAX_20140318T0900.txt",
    "Saxo": "Saxo_20140318T0900.txt"
  },
  "instruments": [
      {
        "instrument_old": "CFH/EURUSD",
        "instrument_new": "LMAX/EURUSD"
      },
      {
        "instrument_old": "CFH/EURUSD",
        "instrument_new": "Saxo/EURUSD" 
      },
      {
        "instrument_old": "LMAX/XAUUSD",
        "instrument_new": "Saxo/XAUUSD" 
      }
  ]
}

我有:

  • shiftData list包含三个元素(min,max和stepShift)
  • 带密钥的字典:value => {provider_name:filename}
  • 名为instrumentPairList
  • 的两个元素列表[instrument_new,instrument_old]的列表

我不希望任何人解决我的任务,但在我的案例中,有关Python中JSON的各种教程相当模糊或简单:

它正在尝试序列化minShift,maxShift,stepShift和feed:

data = { "minShift":shiftData[0],"maxShift":shiftData[1],"stepShift":shiftData[2],
          "feeds":[ {key: value} for key, value in providerAliases.items() ] }
  data_string = json.dumps(data)

1 个答案:

答案 0 :(得分:0)

我的解决方案是:

data = { "minShift":shiftData[0],"maxShift":shiftData[1],"stepShift":shiftData[2],
          "feeds":providerAliases,
           "instruments":[ {"instrument_old":pair[0],"instrument_new":pair[1]}
                            for pair in instrumentPairList ]}
data_string = json.dumps(data, indent=4)

file = open(dir+r"\config.json","w")
file.write(data_string)
file.close()