将openstruct数组转换为json

时间:2017-03-20 11:25:42

标签: json ruby

我有两个形式的openstruct数组:

<OpenStruct id=0, name="EMGEE CABLES AND COMMUNICATIONS LIMITED", group=3>
<OpenStruct id=1, name="ELECTRICAL TECHNOLOGY PARK OF INDIA", group=2>
<OpenStruct id=2, name="PRISM BUILDCON PRIVATE LIMITED", group=2>
....

<OpenStruct source=79, target=3, value=5>
<OpenStruct source=80, target=0, value=5>
<OpenStruct source=81, target=0, value=5>
....

我的目标是将此数据转换为json格式,并将结果保存为以下格式的文件:

{
  nodes:
   [
     {id=0, name="EMGEE CABLES AND COMMUNICATIONS LIMITED", group=3},
     {id=0, name="ELECTRICAL TECHNOLOGY PARK OF INDIA", group=3},
     {id=0, name="PRISM BUILDCON PRIVATE LIMITED", group=3}
   ]
  links:
   [
     {source=79, target=3, value=5},
     {source=80, target=0, value=5},
     {source=81, target=0, value=5}
   ]

}

1 个答案:

答案 0 :(得分:0)

我说你会在你的结构中覆盖你喜欢的.to_json方法。

或者,.to_h method on OpenStruct可以完成您想要的任务。所以.to_h.to_json也应该达到你的目标。

如果你的问题是如何实现所需的输出,你可以这样做:

the_json = {
  nodes: your_first_array_of_structs.map(&:to_h),
  links: your_second_array_of_structs.map(&:to_h)

}.to_json
File.open('path/to/file.json, 'w') { |file| file.write(the_json) }