3

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

6
  • 1
    for (var p in data) { console.log(data[p][0].name); } Commented Jan 31, 2016 at 12:49
  • @A.Wolff this is work like what i want. but what does the (p) then? Commented Jan 31, 2016 at 12:57
  • @GiantApe p is the index. Commented Jan 31, 2016 at 12:58
  • @PraveenKumar , i see thank you soooo much for the explanation. Commented Jan 31, 2016 at 13:02
  • No p is the object property/key Commented Jan 31, 2016 at 13:04

1 Answer 1

3

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);

Sign up to request clarification or add additional context in comments.

2 Comments

@jcubic, thank you so much for the sollution, insted of plan json so i have to save them into a variable first?
thank you All, thank you so much for teaching me. now is working like what i want. thank you once again!.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.