【发布时间】:2017-02-18 20:27:37
【问题描述】:
我正在使用 csv 到 json 转换器,但它弄乱了我的对象顺序。我尝试了不同的转换脚本,但它们都弄乱了顺序。 我的 csv 是这样排序的:
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 文件中。
【问题讨论】:
-
是否有其他解决方案,因为我无法让它以这种方式工作。 sort_keys=True 有效,但我不希望它按字母顺序排列。我想要一个从 csv 文件中读取的自定义订单,因为标题可能会更改
-
看第二个例子(OrderedDict)。
-
虽然请注意,在读取 CSV 时元素的顺序会丢失,因此您需要先在那里解决它。
-
@glibdud 你能帮我实现它吗?此时我有 csv_rows.OrderedDict([("Group-of-Signals name"),("Group-of-Signals description"),("Signal name"),("Signal data type"),("Signal测量单位"),("信号描述"),("信号 ID"),("信号索引")]) 但这不起作用
标签: json python-2.7 csv