Giant Ape
Giant Ape

Reputation: 85

json, ajax with a hash

i wondering if there any solution to get data from json in this format:

{ "#<Hashie::Mash acceptance_type=1 id=79 name=\"template 1\" url=\"http://myDomain\">":[{"id":68,
     "name":"johnny",
     "description":"Hello my first Description",
     "created_by_user_id":16530,
     "created_at":"2016-01-28T13:17:51.827Z",
     "updated_at":"2016-01-29T10:40:40.011Z",
     "receiver_group_id":3,"dynamic_fields":{  
        "files":[  
           {  
              "id":2,
              "date":"2016-01-29T10:40:35.720Z",
              "path":"http://mayDomain/000/000/002/original/The_Idiot.pdf?1454064035",
              "public":null
           }
        ]} }]}

like i want to have a name and description. but if i call in ajax like this:

$(function(){
    $.ajax({
        url: './dataModel.json',
        dataType: 'json',
        method: 'GET',
        success: function(data){

            console.log(data[0].name);// error name is not defined
            console.log(data.name); // undefined
        }
    });
})

may be you guys have some idea how can i get the name and description? thank you so much for any kind of suggestion and idea. best regard, ape

Upvotes: 3

Views: 277

Answers (1)

jcubic
jcubic

Reputation: 66488

Try this:

var input = {
  "#<Hashie::Mash acceptance_type=1 id=79 name=\"template 1\" url=\"http://myDomain\">": [{
    "id": 68,
    "name": "johnny",
    "description": "Hello my first Description",
    "created_by_user_id": 16530,
    "created_at": "2016-01-28T13:17:51.827Z",
    "updated_at": "2016-01-29T10:40:40.011Z",
    "receiver_group_id": 3,
    "dynamic_fields": {
      "files": [{
        "id": 2,
        "date": "2016-01-29T10:40:35.720Z",
        "path": "http://mayDomain/000/000/002/original/The_Idiot.pdf?1454064035",
        "public": null
      }]
    }
  }]
};
var output = Object.keys(input).map(function(key) {
  return input[key];
})[0];
alert(output[0].name);

Upvotes: 3

Related Questions