-2

I am getting JSON data like below example. Now I want get each value in separate variables like

var reviewDate ='2015-06-01T05:00:00Z'

var developers ='Ankur Shah,Srikanth Vadlakonda,Tony Liu, Qiuming Jie

var reviewers = 'mike,john'

var title='Test project'

 var call =$.ajax({
    url:url,
    type:"GET",
    dataType:"json",
    headers:{
        Accept:"application/json;odata=verbose"
    }
 });
 call.done(function(data,textStatus,jqXHR){
     alert("Success!! "+ jqXHR.responseText);
 });
 call.fail(function(jqXHR,textStatus,errorThrown){
      alert("Error retriving Tasks!! "+ jqXHR.responseText);
 });

enter image description here

I am getting results in call.done in . How to set those values?

James123
  • 11,184
  • 66
  • 189
  • 343
  • 2
    You appear to be asking how to access properties of objects, how to loop over arrays, how to assign variables and how to concatenate strings. This is quite a big collection of very basic tasks and you'd probably be better off starting with an introductory JavaScript tutorial. – Quentin May 15 '15 at 19:48
  • 2
    See stackoverflow FAQ: [Access / process objects, arrays or JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Yogi May 15 '15 at 19:53
  • At it's most basic you need to declare the variables outside of the done callback and assign the values within it using the JSON object that came back. How to group the data together in such a way to get it into the variables how you want could be done a few different ways and it's hard to say which would be best based on the information provided. – aaronjkrause May 15 '15 at 19:58

2 Answers2

0

You could do something along these lines:

http://jsfiddle.net/e0mfc1rd/2/

Javascript:

    var data = {
    results: {
        Date_x0020_of_x0020_Review: '2015-06-01T05:00:00Z',
        Name_x0020_of_x0020_Developers: {
            results: [
                {
                    __metadata: {},
                    Title: 'Ankur Shah'
                },
                {
                    __metadata: {},
                    Title: 'Tony Liu'
                },
                {
                    __metadata: {},
                    Title: 'Qiuming Jie'
                }
            ]
        },
        Name_x0020_of_x0020_Reviewers: {
            results: [
                {
                    __metadata: {},
                    Title: 'Mike'
                },
                {
                    __metadata: {},
                    Title: 'John'
                }
            ]
        }
    }
}

// map the key names.
// you could do something more clever here, like just extracting
// the segment after the last underscore using substring or a regex,
// but for this example we'll do a simple map.
var names = {
    'Name_x0020_of_x0020_Reviewers': 'reviewers',
    'Name_x0020_of_x0020_Developers': 'developers'
}

// a variable to hold the result.
var processed = {};

// iterate over each key in data.results
// (e.g. 'Name_x0020_of_x0020_Developers', 'Name_x0020_of_x0020_Reviewers', etc.)
Object.keys(data.results).forEach(function(k) {
    // if the object indexed at that key has a 'results' property that is an array...
    if (Array.isArray((data.results[k] || {}).results)) {
        // pluck the Title attribute from each of those entries into a new array.
        var values = data.results[k].results;
        var titles = values.map(function(v) {
            return v.Title;
        });

        // translate keys like 'Name_x0020_of_x0020_Reviewers'
        // into something more palatable
        var key = names[k] || k;

        // join the titles into a string, separated by a comma
        processed[key] = titles.join(',');
    }
    else if (k.indexOf('Date') === 0) { // key starts with 'Date'
        processed[k] = new Date(data.results[k]);
    }
});

After which the variable 'processed' would contain:

{
    "Date_x0020_of_x0020_Review": "2015-06-01T05:00:00.000Z",
    "developers": "Ankur Shah,Tony Liu,Qiuming Jie",
    "reviewers": "Mike,John"
}
ray
  • 26,557
  • 5
  • 28
  • 27
0

You could also use UnderscoreJS to get your data from your JSON.

You need to chain some pluck calls and you should get to your data.

Please find the demo below and here at jsFiddle.

To get the parsed object into your comma separated format just use for example: var developers = parsed.developers.join(',');

var resultJSON = {
    d: {
        __metadata: {},
            "Name_x0020_of_x0020_Developers": {
            "results": [{
                "Title": "Ankur Shah"
            }, {
                "Title": "Srikanth"
            }, {
                "Title": "Tony Liu"
            }]
        },
            "Name_x0020_of_x0020_Reviewers": {
            "results": [{
                "Title": "Name1"
            }, {
                "Title": "Name2"
            }, {
                "Title": "Name3"
            }]
        }
    }
};

//console.log(resultJSON);

var names = {
    developers: 'Name_x0020_of_x0020_Developers',
    reviewers: 'Name_x0020_of_x0020_Reviewers'
};

var parsed = {};

_.each(names, function (name, key) {
    parsed[key] = _.chain(resultJSON) // key is developers, reviewers
        .pluck(name) // is the name in the JSON e.g. Name_..._Developers
        .pluck('results')
        .tap(function (data) { // tap is optional and can be removed
            console.log('before flatten', data); // it shows the nesting [[]]
        })
        .flatten(true) // used to remove outer array
        .tap(function (data) {
            // we now have the result. Next, get the title
            console.log('before getting the Title', data);
        })
        .pluck('Title')
        .value();
});

console.log(parsed);
document.getElementById('output').innerHTML = JSON.stringify(parsed, null, 2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<pre id="output"></pre>
AWolf
  • 8,770
  • 5
  • 33
  • 39
  • The pure js approach from Ray is faster (around 35%) than the Underscore version but I think Underscore is easier to read. Have a look at this performance comparison at [jsperf](http://jsperf.com/plucking-data-from-json) – AWolf May 15 '15 at 22:21