Ruby-on-rails – Merge two JSON with a matching ID in Rails

jsonrubyruby-on-railsruby-on-rails-3

I got two JSON that are structured like this. First one comes from an API:

[
  {
   "course_code":"Basic 101 - 0913",
   "name":"Basic 101",
   "start_at":"2013-09-16T00:00:00+02:00",
   "end_at":"2013-10-13T23:55:00+02:00",
   "workflow_state":"available"
  },
  {"course_code":"Medium 201 - 0913",
   "name":"Medium 201",
   "start_at":"2013-08-06T16:55:25+02:00",
   "end_at":null,
   "workflow_state":"available"
  }
]

The second one is a JSON export from my database:

[
  {
   "id":1,
   "course_id":"Basic 101",
   "name":"Basic Level",
   "description":"blablabla",
   "discipline_id":"1",
   "duration":"28",
   "created_at":null,
   "updated_at":null
  },
  {
   "id":2,
   "course_id":"Medium 201",
   "name":"Medium Level",
   "description":"blablabla",
   "discipline_id":"1",
   "duration":"28",
   "created_at":null,
   "updated_at":null
  }
]

I would like to merge these two JSON into one, with matched :name in the first JSON and :course_id in the second one.

If you know good tutorials on using JSON in Rails, I'm really interested.

Best Answer

This isn't really a JSON issue.

When parsing JSON data it returns arrays and hashes.

One way of merging it in this case would be to loop through the data and check for the parameters you want/need to match. Once you find a match you can either manually create a new Hash with the needed data or you could use

hash1.merge(hash2)

http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-merge

which would return a hash consisting of both Hashes - attributes with the same name would be overwritten in the first hash.