Terri
Terri

Reputation: 352

How to separate a JSON.stringify result

Related Retrieve two lists, sort and compare values, then display all the results

The question in the related post was how to combine two lists and sort them. The code referenced each item on each list. So, when I got the result, I could manipulate it.

The best solution used console.log(JSON.stringify(result,null,2)); to return the result, nicely combined and sorted.

Trouble for me is being able to translate that back into something I can work with. I can get the result into a variable and display it on the page, but it's the raw output : [ { "Title": "apple", "Type": "rome", "State": null }, ...

Have tried 'JSON.parse(result);' where result is the variable that is used to handle the combination and sorting of the two lists. All that gives is an invalid character error on the line. Also looked at the 'replace' option. That just confused me, tmi. Tried setting a variable directly on the result (so those who know are laughing) 'var foo = result;' That returns object, object.

The desired end result would be to end up with each item separate so I can put them in a table (or a list) on my html page with blanks in any column where there is no data.

I know there has to be a simple, easy way to do this without 200 lines of transformation code. But I can't find a clear example. Everything I'm seeing is for +experts or uses a super simple array that's typed into the code.

Is there a way to attach something like this (from my original) to the result instead of using JSON.stringify? What other step(s) am I missing in being able to extract the fields from JSON.stringify using JSON.parse?

}).success(function (data) {

    var title = '';
    var type = '';
     $.each(data.d.results, 
    function (key, value) {

    title += "Title: " + value.Title + "<br/>";
    type += "Type: " + value.Type  + "<br/>";
    }); 

$("#tdtitle").html(title);
$("#tdtype").html(type);

Upvotes: 0

Views: 2153

Answers (1)

Gavriel
Gavriel

Reputation: 19237

Terry, you wrote: "All that gives is an invalid character error on the line"? Then result is not a valid json. Test it here: http://jsonlint.com/, fix it, then try again.

var data = {
  d:{
    results: [
      { "Title": "apple", "Type": "rome", "State": null }, 
      { "Title": "grape", "Type": "fruit", "State": null }
    ]
  }
};

var title = '';
var type = '';
$.each(data.d.results, function (index, value) {
    title += "Title: " + value.Title + "<br/>";
    type += "Type: " + value.Type  + "<br/>";
}); 

alert(title + type);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 3

Related Questions