1

I'm trying to replace the angularjs POST query with standalone JSON response string.

When angular GET / POST queries returns a response automatically converted to JSON and the code was working like charm.

Now, I'm trying to have the json response stored as a javascript string variable in the controller and then trying to parse it using JSON.stringify() and subsequently using JSON.parse().

There is no error but the resulting json object's member variables can't be accessed using the . operator

var staticData = '{"someKey":"someValue", "masterJobs":[]}'; //very large json string.
var resultString = JSON.stringify(staticData);
$scope.staticTestData = JSON.parse(resultString);
console.log($scope.staticTestData.masterJobs); // this displays 'undefined'

Controller function with the large JSON is available here.

Arount
  • 9,853
  • 1
  • 30
  • 43
Adi Das
  • 21
  • 3

1 Answers1

3

You already have a string, so there is no need to use JSON.stringify.

Just use the following code:

var staticData = '{"someKey":"someValue", "masterJobs":[]}'; //very large json string.
$scope.staticTestData = JSON.parse(staticData);
console.log($scope.staticTestData.masterJobs);
str
  • 42,689
  • 17
  • 109
  • 127
  • I tried that already. This is the error I get when I parse the string without doing the JSON.stringify()
    SyntaxError: Unexpected token in JSON at position 1323 at JSON.parse () at searchFunction (SummaryReport.html:249) at new (SummaryReport.html:262) at Object.invoke (angular.min.js:41) at P.instance (angular.min.js:89) at n (angular.min.js:65) at g (angular.min.js:58) at angular.min.js:58 at angular.min.js:21 at m.$eval (angular.min.js:145)
    – Adi Das Aug 01 '17 at 03:47
  • Have a look at the exact position of the error and you will find this section `"tsdescription":"
    DISPLAYED
    \n
    \nPassed"`. It contains new lines `\n` which will cause your string to actually have new lines in it (and not inside the value). You need to escape them, see https://stackoverflow.com/questions/11591784/parsing-json-containing-new-line-characters for details.
    – str Aug 01 '17 at 08:27
  • That helped!! But it is now failing at this point: "xmlLogFilePath": "\\\\cable.comcast.com\\corp-dfs\\CHQ-Shared\\BSD-TCoE\\Logs\\WEBTOP\\TACGWC-WBTP02\\Parent_WEBTOP_ONECLICK_MASTER_8\\testng_simon_SimonMACD_OneClick" Do you see anything wrong with the escaped url? – Adi Das Aug 01 '17 at 14:42