Transform JSON string into a knockout observable array

I have a JSON string that I need to convert into a knockout.js observable array.

Here is the JavaScript code I am currently using:

$(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 the HTML structure:

<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>

After making an ajax call, I receive a JSON response from the server and I want to bind this data to an HTML table.

I attempted to use ko.mapping.fromJs() to convert the JSON to an observable array but encountered the following error:

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

The JSON response looks like this:

[
 {"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}
]

What adjustments can be made to the code to ensure the proper conversion of the JSON string into a Knockout.js observable array?

Answer №1

Try this code snippet:

var data = [{"id":1,"name":"John","status":"active"},{"id":2,"name":"Jane","status":"inactive"}];

var ViewModel = function() {
    this.items = ko.observableArray(ko.mapping.fromJS(data)());
        console.log(this.items());
};
ko.applyBindings(new ViewModel()); 

Make sure to use $data in your view structure, instead of $parent.

You can see a working example on this JSFiddle link.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React does not support the map function

I've been struggling for three days to figure out why I am unable to place multiple elements in an array. Interestingly, when I try to access only one element using this.state.dat.nombre or dat.carrera, it works perfectly fine. However, when I attempt ...

What is the best way to set a default selected option in an ng-multiselect-dropdown using Angular?

Here, I am retrieving data from the database and storing it in an events array. The data in this events array is displayed on the book-ticket.component.html using ng-multiselect-dropdown. Upon selecting an option, the corresponding data is stored in this.e ...

A step-by-step guide on inserting a date into a MongoDB database using data from

I have a JSON file that contains an object with a date. How can I ensure that this date field is correctly inserted as a "date" data type in MongoDB? This needs to be achieved using Node.js. { "name": "Jeff Johnson", "email": "<a href="/cdn-cg ...

Is it possible to create a drop and bounce effect for an image using JQuery (without flash)?

Greetings everyone, I'm a newcomer here with minimal experience in JQuery and coding. So please be gentle :) Currently, I am working on creating a launch page for a series of websites, which will consist of a mix of Joomla and Wordpress sites. The ma ...

Incorporating input fields into an HTML form

I'm looking to enhance my form by adding input fields dynamically through the JavaScript function when I click on the add button: let i = 0; function increment() { i += 1; } function addFieldFunction() { let newDiv = document.createElement(&apos ...

"Seeking assistance in pinpointing a memory leak issue within an Express application running

The issue at hand My Node application running in ECS seems to be experiencing memory leaks, with the memory continuously growing and dropping after each deployment. To investigate further, I generated a heapdump and imported it into Chrome DevTools for a ...

Methods for submitting POST requests with key data enclosed in quotation marks?

Upon investigation, I discovered that the Request Payload object's key does not have quotation marks as shown below. https://i.sstatic.net/U54V9.png However, I am interested in sending a request with keys that are marked with quotations. Interestingl ...

numerous ajax requests and array variables

I find myself in an interesting situation with my application, where I need to handle a couple of scenarios. Firstly, I have to fetch data from two different sources using AJAX calls. Secondly, I need to compare and manipulate this data. If the values matc ...

Retrieve the current window width in order to fetch the most up-to-date

Is there a way to dynamically update the param value in an ajax request based on the width of the window, allowing for different actions on smaller devices? I'm facing the issue where the window width is only captured on page load and does not get up ...

What is the best way to ensure that the input submit element is only visible after the input checkbox element has been checked?

For a school project, I am attempting to create a simulated reCAPTCHA box. Although my code is complete, I would like the functionality to submit your response from the input fields above only after selecting the reCAPTCHA checkbox. Upon researching, it ap ...

jQuery-powered Ajax file upload progress bar

Although I don't rely on jQuery for everything, I do find it useful for tasks such as AJAX. But currently, I'm facing some challenges with it. Here is a piece of code that should update my upload progress bar while the upload process is ongoing. ...

The Express API will only provide the initial key-value pair of an object in the response

I'm working on fetching nested data objects. Although I can successfully retrieve the object data in the console, I encounter an issue when attempting to access this data using return res.json(imageObject). Instead of retrieving all key-value pairs of ...

UTF-8 characters not displaying correctly in Python 3 when received through WebSocket?

I am encountering an issue with sending a JavaScript unicode star character. When interpreted by Python, the unicode characters are being displayed as the letter â, both in the console and log file. Furthermore, other unicode characters also seem to be ...

Tips on leveraging dynamic queries in your REST API usage

As a new Javascript learner, I am experimenting with creating a basic rest api using node.js. Currently, I have set up a database called testDb and a table named testMeasurement in influxdb. The testMeasurement table consists of the columns DateOfBirth, ID ...

Issue: [next-auth]: `useSession` function should be enclosed within a <SessionProvider /> tag in order to work properly

Encountering an error loading my ProfilePage where the page loads fine in the browser but an error appears in the terminal. Error: [next-auth]: `useSession` must be wrapped in a <SessionProvider /> All child components are properly wrapped using Se ...

AngularJS and the select2 plugin from Angular-UI: User-selected option doesn't match the displayed selection

When a user chooses an option, a different selection appears as the chosen one. This issue is only present when select2 is enabled. Despite this, ng-model behaves as expected, causing the selected option to differ from what ng-model indicates. Interesting ...

JavaScript's inability to properly export CSV data containing the "#" character has been causing issues

When exporting JSON data to CSV format and downloading it using JavaScript, everything typically works fine. However, there is a problem if the data contains the hash sign #. The function fails to export all the data in that case, for example: This is my ...

What are the various ways to display time zone in a different format?

I need to display the timezone in a unique manner. I have captured the user's timezone in a variable called timeZone, which currently returns the value as Asia/Calcutta. console.log(timeZone) // "Asia/Calcutta" Is there a way to showcase the timezon ...

Uncovering the Android tablet browser: A guide

I have implemented the code below to detect mobile/tablet browsers. function isMobile() { var index = navigator.appVersion.indexOf("Mobile"); return (index > -1); } Although it works well for desktop browsers and iOS devices (iPhon ...

Invalid web address entered

While attempting to incorporate a functionality that opens a new window to a specific link when clicking an icon, I encountered an issue where the click action redirects to the wrong URL. Instead of directing to the URL specified in its href attribute, it ...