ruby - Merge two JSON with a matching ID in Rails -


i got 2 json structured this. first 1 comes 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 1 json export 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 merge these 2 json one, matched :name in first json , :course_id in second one.

if know tutorials on using json in rails, i'm interested.

just quick answer, let know go. assuming first json in json1 , second in json2 variables, code:

require 'json'  arr1 = json.parse(json1) arr2 = json.parse(json2) mrg = [] arr1.each |el1|   arr2.each |el2|     if el2['course_id'] == el1['name']       mrg.push(el1.merge(el2))     end   end end  p mrg 

will print:

[   {    "course_code"=>"basic 101 - 0913",    "name"=>"basic level",     "start_at"=>"2013-09-16t00:00:00+02:00",     "end_at"=>"2013-10-13t23:55:00+02:00",     "workflow_state"=>"available",     "id"=>1,     "course_id"=>"basic 101",     "description"=>"blablabla",     "discipline_id"=>"1",     "duration"=>"28",     "created_at"=>nil,     "updated_at"=>nil   },   {    "course_code"=>"medium 201 - 0913",     "name"=>"medium level",     "start_at"=>"2013-08-06t16:55:25+02:00",     "end_at"=>nil,     "workflow_state"=>"available",     "id"=>2,     "course_id"=>"medium 201",     "description"=>"blablabla",     "discipline_id"=>"1",     "duration"=>"28",     "created_at"=>nil,     "updated_at"=>nil   } ] 

Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -