我已经阅读了python question similar to my problem,但它没有帮助。
我有一个50万行CSV
文件,如下所示:
contract-number,amendment-number,award-date,contract-value,supplier-name,contracting-entity
W8486,0,2014-04-14,14326000,"COMPANY A","Office of Llama Supplies"
W8487,0,2014-04-10,150000,"COMPANY B","Foo Bar Dept"
W8488,2,2014-03-24,146000,"COMPANY C","Armed Forces"
W8488,1,2014-03-03,68000,"COMPANY C","Armed Forces"
W8488,0,2014-02-17,27760,"COMPANY C","Armed Forces"
W8489,0,2014-02-14,51000000,"COMPANY B","Dept of Magical Affairs"
许多合同不止一次出现。
我想编写一个Ruby脚本来将我的数据转换为JSON
文件,该文件嵌套到同一个节点中,那些具有相同编号的合同如下:
[{"W8486":
{0:
{
"award-date": 2014-04-14,
"contract-value": 14326000,
"supplier-name": "COMPANY A",
"contracting-entity": "Office of Llama Supplies"
}
}
},
{"W8487":
{0:
{
"award-date": 2014-04-10,
"contract-value": 150000,
"supplier-name": "COMPANY B",
"contracting-entity": "Foo Bar Dept"
}
}
},
{"W8488":
{2:
{
"award-date": 2014-03-24,
"contract-value": 146000,
"supplier-name": "COMPANY C",
"contracting-entity": "Armed Forces"
}
},
{1:
{
"award-date": 2014-03-03,
"contract-value": 68000,
"supplier-name": "COMPANY C",
"contracting-entity": "Armed Forces"
}
},
{0:
{
"award-date": 2014-02-17,
"contract-value": 27760,
"supplier-name": "COMPANY C",
"contracting-entity": "Armed Forces"
}
},
},
{"W8489":
{0:
{
"award-date": 2014-02-14,
"contract-value": 51000000,
"supplier-name": "COMPANY B",
"contracting-entity": "Dept of Magical Affairs"
}
}
}]
到目前为止,我已设法迭代CSV using CSV.foreach do |line|
,将每个项目放入哈希值。我设法检查了line[0] == previousContractNumber
。
但每次我写JSON文件时,都会收到此错误:
nesting of 100 is too deep (JSON::NestingError)
我怎么能绕过这个?
非常感谢!
答案 0 :(得分:0)
以下是应该工作的一些代码:
result = Hash.new { |h, k| h[k] = {} }
CSV.foreach do |line|
result[line[0]][line[1]] = {
"award-date" => line[2],
"contract-value" => line[3],
"supplier-name" => line[4],
"contracting-entity" => line[5]
}
end