Priyanka Mokashi
Priyanka Mokashi

Reputation: 417

convert json string into knockout observable array

I am trying to convert a JSON string into a knockout.js observable array.

Here is my js code:

$(document).ready(function(e){
    var model =  function(dat){
        this.tabledata = ko.observableArray(dat);
    };

    $.ajax({
        url: 'http://localhost:1141/rest_service/show_data',
        type: 'GET',
        success: function(msg){
            // var dat = JSON.parse(msg);

            alert(msg);
            ko.applyBindings(new model(msg));
        },
        error: function(msg){
            alert(JSON.stringify(msg));
        },
    });
});

and here is my html:

<table id = "example" >
    <thead>
        <tr>
            <th>Employee ID</th>
            <th>Employee Name</th>
            <th>Employee Status</th>
            <th>Date of birth</th>
            <th>Age</th>
        </tr>
    </thead>
    <tbody data-bind='foreach: tabledata'>
       <tr>
           <td data-bind='text: $parent.empId'/></td> 
            <td data-bind='text: $parent.empStatus'/></td>
            <td data-bind='text:$parent.dob'/></td>
            <td data-bind='text: $parent.empName'/></td>
            <td data-bind='text: $parent.age'/></td>
        </tr>
    </tbody>
</table>

So here, after an ajax call, I am getting a JSON string as a response from the server and I want to bind this data to html table.

I tried using ko.mapping.fromJs() to convert the incoming JSON to an observable array but received the following error:

Error: The argument passed when initializing an observable array must be an array, or null, or undefined.

The JSON response is as follows:

[
 {"empId":100,"empName":"TA","empStatus":"yes","dob":"2000-12-12","age":15},   
 {"empId":101,"empName":"TA","empStatus":"yes","dob":"2000-12-12","age":15},
 {"empId":102,"empName":"TATA","empStatus":"yes","dob":"1997-12-12","age":18},
 {"empId":103,"empName":"kljh","empStatus":"yes","dob":"2000-12-12","age":15},
 {"empId":111,"empName":"Aria","empStatus":"No","dob":"1995-10-17","age":20}
]

How can I change my code so that the JSON string is converted properly into a Knockout.js observable array?

Upvotes: 2

Views: 2662

Answers (1)

super cool
super cool

Reputation: 6045

Do something like below

var json = [{"empId":100,"empName":"TA","empStatus":"yes","dob":"2000-12-12","age":15},{"empId":101,"empName":"TA","empStatus":"yes","dob":"2000-12-12","age":15},{"empId":102,"empName":"TATA","empStatus":"yes","dob":"1997-12-12","age":18},{"empId":103,"empName":"kljh","empStatus":"yes","dob":"2000-12-12","age":15},{"empId":111,"empName":"Aria","empStatus":"No","dob":"1995-10-17","age":20}]

var ViewModel = function() {
    this.list = ko.observable(ko.mapping.fromJS(json)());
        console.log(this.list());
};
ko.applyBindings(new ViewModel()); 

In view use $data instead of $parent as per your view structure .

working sample fiddle here

Upvotes: 2

Related Questions