0

How can i transform this instance variable into JavaScript array of objects

I know there is something that i have to do with

but when i try it. it just completely errors out..

This is what i am getting: (comes out with the Quotes)

@updates = [
  "{'24548_0_load_results': ['1630609','2015-04-07 13:51:03 UTC','7 minutes']}", 
  "{'24548_0_load_results': ['1630610','2015-04-07 13:51:03 UTC','7 minutes']}"
]

Created the above with this:

  @updates = []
  records.each do |r|
    updates << "{ '" + t.search_table_id.to_s + "': " + Search.load_post_result(r, s).to_s + " }"
  end

This is how i need it:

var obj1 = {
    "loads": [
        {'24547_1428357240_load_results' : ['1630607','2015-04-06 18:35:46 UTC','8 minutes']},
        {'24547_1428357240_load_results' : ['1630606','2015-04-06 18:35:47 UTC','8 minutes']}
    ]
};

This is the script that i am tring to run this array of objects thru:

$.each(obj1["loads"], function(k, v){
    $.each(v, function(key, value) {
        alert(key + ": " + value);
    })
});

edit: This is what i have now

var obj1 = {
    "loads": []
};

for (string in <%= @updates1 %>){
    obj1["loads"].push(JSON.parse(string.replace(/'/g,'\"')));
}

$.each(obj1["loads"], function(k, v){
    $.each(v, function(key, value) {
        alert(key + ": " + value);
    })
});

And looks like this in the response:

var obj1 = {
    "loads": []
};

for (string in [&quot;{ '24549_1428420484_load_results': ['1630610','2015-04-07 14:44:37 UTC','44 minutes','Springfield, MO','Dallas, TX','04/07','04/07','Full','Flatbed or Van or Reefer','','53','0.00'] }&quot;, &quot;{ '24549_1428420484_load_results': ['1630609','2015-04-07 13:51:03 UTC','about 2 hours','Springfield, MO','Dallas, TX','04/10','04/11','Full','Flatbed or Van or Reefer','','53','0.00'] }&quot;]){
    obj1["loads"].push(JSON.parse(string.replace(/'/g,'\"')));
}

$.each(obj1["loads"], function(k, v){
    $.each(v, function(key, value) {
        alert(key + ": " + value);
    })
})

;

Big Al Ruby Newbie
  • 834
  • 1
  • 10
  • 30

1 Answers1

1

You could do it in javascript like this:

    JSON.parse("YourString".replace(/'/g,'\"'))

Here's a fiddle to demonstrate.

https://jsfiddle.net/ab19ha1o/

You need to replace the single quotes to properly parse JSON, so that's a quick and dirty way to do it :)

Edit: Here's the SO Thread on JSON Parse: jQuery.parseJSON single quote vs double quote

And you would just need to iterate over each string to get the object.

Edit: The full transfer would look something like this:

    for (string in updates){
      obj1["loads"].push(JSON.parse(string.replace(/'/g,'\"')));
    }
Community
  • 1
  • 1
WakeskaterX
  • 1,408
  • 9
  • 21