-1

I need to create an array of objects, with each object containing fields "LicenseRefNo", "FPPRNO" etc.

The website makes an ajax call to a C# controller which currently returns the following json:

"[{\"LicenseRefNo\":\"17/00031/HMO\",\"FPPRNO\":\"AGE146\"},{\"LicenseRefNo\":\"16/00031/HMO\",\"FPPRNO\":\"AGE146\"}]"

This seems to be almost correct but I need to set this as a gridOptions.data property of a KOGrid. It seems the javascript code is then running into a problem because the KOGrid needs to be an observable array, and to create one of these I need a javascript array.

How can I convert the string I have into an array please?

Rob Bowman
  • 7,632
  • 22
  • 93
  • 200
  • I just knew this question would get down voted! I realise this is a JS newbie question but got to start somewhere! – Rob Bowman Jun 12 '17 at 14:44
  • Possible duplicate of [Parse JSON in JavaScript?](https://stackoverflow.com/questions/4935632/parse-json-in-javascript) – JJJ Jun 12 '17 at 14:56

3 Answers3

5

JSON.parse(string) should do the trick

Titouan56
  • 6,932
  • 11
  • 37
  • 61
  • Hmmm... Not sure because of the second double-quote : `"["{\"LicenseRefNo\"` . The inner object is also inside double-quotes, that may be trickier than expected. If you try to `JSON.parse` that, it throws : `Uncaught SyntaxError: Unexpected token L in JSON at position 4` – Jeremy Thille Jun 12 '17 at 14:43
2

The JSON sample you posted is invalid, some quotes are weird and JSON.parse won't work directly. Here is a valid JSON content:

"[{\"LicenseRefNo\":\"17/00031/HMO\",\"FPPRNO\":\"AGE146\"},{\"LicenseRefNo\":\"16/00031/HMO\",\"FPPRNO\":\"AGE146\"}]"

Are you sure the content you posted is what you get? It's not even a valid string.

sjahan
  • 5,720
  • 3
  • 19
  • 42
1

OberservableArray ships with knockout and you can create one with

edit: I created a fiddle with a working example since the posted seemed to be broken

var viewModel = function() {
    var yourLoadedArray =[{"LicenseRefNo":"17/00031/HMO","FPPRNO":"AGE146"},{"LicenseRefNo":"16/00031/HMO","FPPRNO":"AGE146"}]; 
   this.obsArr = ko.observableArray(yourLoadedArray);
    this.test = "test";
};

 
ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<span data-bind="text: test"></span>
<div  data-bind="foreach: obsArr">
  <span  data-bind="text: LicenseRefNo"></span>
</div>
subkonstrukt
  • 446
  • 2
  • 15
  • Did you try this code? It throws `Uncaught SyntaxError: missing ) after argument list` because of the unescaped second quote. – Jeremy Thille Jun 12 '17 at 14:48