2016-10-10 17 views
0

我正在使用csv到json轉換器,但它弄亂了我的對象順序。我嘗試了不同的轉換腳本,但他們都搞亂了順序。 我的CSV訂購這樣的:對象json文件的順序

Group-of-Signals name,Group-of-Signals description,Signal name,Signal data type,Signal unit of measurement,Signal description,Signal ID,Signal index 

但是在轉換後它看起來像這樣:

[{ 
    "Signal ID": "-1", 
    "Group-of-Signals description": "", 
    "Signal index": "0", 
    "Signal name": "EUVPulseCount", 
    "Signal unit of measurement": "M", 
    "Signal data type": "SDT_STRING", 
    "Signal description": "", 
    "Group-of-Signals name": "DPI_0" 
}] 

我想有這樣的:

[{ 
    "Group-of-Signals name" : "DPI_0", 
    "Group-of-Signals description" : "", 
    "Signal name" : "EUVPulseCount", 
    "Signal data type" : "SDT_STRING", 
    "Signal unit of measurement" : "M", 
    "Signal description" : "", 
    "Signal ID" : "-1", 
    "Signal index" : "0" 
}] 

我已經包括代碼在這裏,所以它不會是一個凌亂的問題:https://codeshare.io/B0KyP

我檢查編輯答案在這裏:Items in JSON object are out of order using "json.dumps"?但我不能得到它的工作。

更新: 我還沒有工作。所有的解決方案都是關於加載JSON文件的。在我的情況下,我不加載JSON文件。我將數據轉儲到新創建的JSON文件中。

+0

的[?在JSON對象的項目是出於使用 「json.dumps」 爲了]可能的複製(http://stackoverflow.com/questions/10844064/items-in- json-object-is-out-of-order-using-json-dumps) – glibdud

+0

有沒有另一種解決方案,因爲我無法以這種方式工作。 sort_keys = True有效,但我不希望它按字母順序排列。我想要一個自定義的訂單,它是從csv文件中讀出的,因爲標題可能會改變 –

+0

看看第二個例子(OrderedDict)。 – glibdud

回答

0

使用OrderedDict

import csv 
import json 
from collections import OrderedDict 

def whatever(filename): 
    r = [] 
    with open(filename, 'r') as fp: 
     reader = csv.reader(fp) 
     headers = next(reader) 
     for row in reader: 
      data = OrderedDict(zip(headers, row)) 
      r.append(data) 
    return json.dumps(r)