-1

Can somebody give me some guidelines how to serialize data to file similar to presented below?

{
  "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" 
      }
  ]
}

I have:

  • shiftData list with three elements (for min, max and stepShift)
  • dictionary with key:value => {provider_name : filename}
  • list of two element lists [instrument_new, instrument_old] named instrumentPairList

I don't want nobody to solve my task, but various tutorials on JSON in Python are rather blurred or to simple in my case:

It is trying to serializing minShift, maxShift, stepShift and feeds:

data = { "minShift":shiftData[0],"maxShift":shiftData[1],"stepShift":shiftData[2],
          "feeds":[ {key: value} for key, value in providerAliases.items() ] }
  data_string = json.dumps(data)
Community
  • 1
  • 1
CppMonster
  • 1,216
  • 4
  • 18
  • 35
  • 6
    Please show us the Python code you have tried and tell us what works and what doesn't work. –  Apr 04 '14 at 15:00
  • The question doesn't make sense - dumping data to JSON is achieved in your example and you have solved how to build the required data structure. Unless I'm missing something, there's nothing else to working with JSON unless you have a pythonic object which isn't supported JSON serialization – Euan Apr 04 '14 at 15:14
  • 1
    you might consider to simply use `"feeds":providerAliases` to mimic the datas in you example. json knows how to serialize dictionnaries. – FabienAndre Apr 04 '14 at 15:17
  • @FabienAndre you're right it's serializing this data properly, there remains to serialize instruments. – CppMonster Apr 04 '14 at 15:28
  • 2
    your issue is how to convert your `[instrument_new, instrument_old]` lists into *"instruments"* list shown above. It has nothing to do with json. `L = [dict(intsrument_old=old, instrument_new=new) for new, old in instrumentPairList]` – jfs Apr 04 '14 at 15:42
  • Yes your solution is correct it works. But I have still question. How to remain order of serialized elements in which I added them? – CppMonster Apr 04 '14 at 15:44

1 Answers1

0

My solution is:

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()
CppMonster
  • 1,216
  • 4
  • 18
  • 35