CSV 到 JSON Ruby 脚本?
有谁知道如何编写将 csv 文件转换为 json 文件的 Ruby 脚本?
CSV 将采用以下格式:
Canon,Digital IXUS 70,"Epic, Epic 100",3x,Yes (lockable),Yes (lockable),Yes
Canon, Digital IXUS 75,"Epic, Epic 100",3x,Yes (lockable),Yes (lockable),Yes
Canon,Digital IXUS 80,"Epic, Epic 100",3x,Yes (lockable),Yes (lockable),Yes
JSON 将需要产生以下结果:
{ "aaData": [
[ "Canon" , "Digital IXUS 70" , "3x" , "Yes (lockable)" , "Yes (lockable)" , "Yes"],
[ "Canon" , "Digital IXUS 75" , "3x" , "Yes (lockable)" , "Yes (lockable)" , "Yes"],
[ "Canon" , "Digital IXUS 80" , "3x" , "Yes (lockable)" , "Yes (lockable)" , "Yes"]
]}
Does anyone know how to write a Ruby script that would convert a csv file to a json file?
The CSV would be in this format:
Canon,Digital IXUS 70,"Epic, Epic 100",3x,Yes (lockable),Yes (lockable),Yes
Canon, Digital IXUS 75,"Epic, Epic 100",3x,Yes (lockable),Yes (lockable),Yes
Canon,Digital IXUS 80,"Epic, Epic 100",3x,Yes (lockable),Yes (lockable),Yes
and the JSON would need to result in this:
{ "aaData": [
[ "Canon" , "Digital IXUS 70" , "3x" , "Yes (lockable)" , "Yes (lockable)" , "Yes"],
[ "Canon" , "Digital IXUS 75" , "3x" , "Yes (lockable)" , "Yes (lockable)" , "Yes"],
[ "Canon" , "Digital IXUS 80" , "3x" , "Yes (lockable)" , "Yes (lockable)" , "Yes"]
]}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这在 ruby 1.9 中很容易,其中 data 是 csv 数据字符串
This is easy in ruby 1.9 where data is your csv data string
来源: 执行
此操作
:
信用: https://technicalpickles.com/posts/parsing -csv-with-ruby
To go from:
To
Do this:
Credit: https://technicalpickles.com/posts/parsing-csv-with-ruby
在 Josh 的示例的基础上,您现在可以使用 CSV::table:
现在您可以调用
to_json
立即使用它,或者将其写入格式良好的文件中:Building on Josh's example, you can now take it one step further using CSV::table:
Now you can call
to_json
to use it right away, or write it down to a file, nicely formatted:如果您在 Rails 项目中
If you're in a Rails project
我的解决方案以这种方式结束,与 Mariu 的非常相似
My solution ended up this way, quite similar to Mariu's