Using Knockout to Bind Complex JSON Data to View Model

I am struggling to connect a KnockoutJS view model with a JSON string that represents a 2D array. Unfortunately, only the first level of the array is showing up.

Here is how my model is structured:

function CategoriesModel(categories) {
    var self = this;

    self.categories = ko.observableArray(ko.utils.arrayMap(categories, function (category) {
        return {
            description: category.description,
            checks: ko.observableArray(category.checks)
        };
    }));

    self.addCategory = function () {
        self.categories.push({
            description: "",
            checks: ko.observableArray()
        });
    };

    self.removeCategory = function (category) {
        self.categories.remove(category);
    };

    self.addCheck = function (category) {
        category.checks.push({
            description: "",
            keypoint: "",
            penaltypoints: ""
        });
    };

    self.removeCheck = function (check) {
        $.each(self.categories(), function () {
            this.checks.remove(check)
        });
    };

    self.save = function () {
        self.lastSavedJson(JSON.stringify(ko.toJS(self.categories), null, 2));
    };

    self.lastSavedJson = ko.observable("");
};

The issue arises when I attempt to bind the JSON data in the following method:

function loadData() {
    var rawJSON = '[
        {
            "description":"01", 
            "checks":{"
                    description":"01", 
                    "keypoint":"01", 
                    "penaltypoints":"01"
            }
        },{
            "description":"02", 
            "checks":{
                    "description":"02", 
                    "keypoint":"02", 
                    "penaltypoints":"02"
            }
        }
    ]';

    var parsedJSON = JSON.parse(rawJSON);

    viewModel.categories = ko.mapping.fromJSON(rawJSON);

    ko.applyBindings(viewModel);
}

I would appreciate any insights on where I might be going wrong. Thank you for your help.

Edit: I attempted to create a jsfiddle (http://jsfiddle.net/EAu2E/4/) but it appears that knockout.js and knockout-mapping.js resources are not loading correctly.

Answer №1

The issue stemmed from the JSON string structure. Despite http://jsonlint.com indicating that the following string was valid:

var rawJSON = '[
    {
        "description":"01", 
        "checks":{"
                description":"01", 
                "keypoint":"01", 
                "penaltypoints":"01"
        }
    },{
        "description":"02", 
        "checks":{
                "description":"02", 
                "keypoint":"02", 
                "penaltypoints":"02"
        }
    }
]';

The Knockout JS framework required square brackets around the nested list (valid JSON), like so:

var rawJSON = '[
    {
        "description":"01", 
        "checks":[{"  //<----- Square bracket needed here.
                description":"01", 
                "keypoint":"01", 
                "penaltypoints":"01"
        }]  //<----- Square bracket needed here.
    },{
        "description":"02", 
        "checks":[{  //<----- Square bracket needed here.
                "description":"02", 
                "keypoint":"02", 
                "penaltypoints":"02"
        }]  //<------ Square bracket needed here.
    }
]';

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

When I click the login button, a .ttf file is being downloaded to my computer

I have encountered an issue with my web application where custom font files in .ttf, .eot, and .otf formats are being downloaded to users' local machines when they try to log in as newly registered users. Despite attempting various solutions, I have b ...

Switching from a functional component to a class component in React

I need assistance converting a code snippet from using functional components with useEffect to a class component. Can someone please help me with this task? import * as React from "react"; export default class App extends React.Component { c ...

The Position of the WebGL Globe Within the Environment

I've been experimenting with the WebGL Globe, and I have successfully made it rotate. However, I'm struggling to figure out how to adjust its position so that it's not centered in the scene. After making changes to the code found at https:/ ...

I am looking to identify which tabs are active based on the current day using vuejs

With 7 tabs on my Vue.js page, I aim to activate the tab corresponding to the current day. However, I am facing a challenge where only the active tab is being highlighted and not allowing me to navigate to others after applying if-else statements. How can ...

What is the best way to establish a JavaScript function at the global level?

I need to make my function accessible globally in JavaScript. How can I accomplish this? Below is the function that I have: $(function () { function formatCurrency(input) { return input.toString().replace(/(\d)(?=(\d{3})+(?!\d) ...

Ajax dropdown menu displaying 'Loading Data' message during processing

Is it possible to display a Please wait.. or Loading... label underneath my Combo box while data is loading? I would like to show a Loading... message under the switch box when switching between Male and Female. https://i.sstatic.net/zpFDF.jpg This is th ...

Modifying the page's left attribute dynamically with jQuery based on window resize

I am currently facing a small issue with my code. My goal is to update the 'left' CSS property of certain elements based on the difference between their current left value and the page resize amount. This way, when the background moves with a pag ...

The noclose feature in Twitter Bootstrap is malfunctioning when placed within a div

I have a PHP page named a.php that contains the following code: <ul class="dropdown-menu noclose"> This code functions correctly, preventing the drop-down menu from closing until the user clicks outside the box. However, when I load the entire a.p ...

Performing a JavaScript array calculation on data retrieved from a database

Can someone help me with automatically calculating values using the onchange event in text boxes? I need to calculate the total based on input from an array in a database using the onchange event. HTML : <td class="text-left"><input type="text ...

Is it possible to invoke a webmethod on an external site using JSONP?

I've been attempting to call an external website's webmethod and post some data, but despite trying various methods, I haven't been successful in getting the method to execute. Below is my JavaScript code: $.ajax({ url: "http:/ ...

Vue.js | Dynamically add a new key and value pair to an array being built using $ajax

Currently, our goal is to implement a calendar using Vue.js where the values are fetched via an $ajax call. Following this, I aim to manipulate some of the children's data in Vue.js. I've spent over 2 hours trying to discover a suitable method f ...

Tips for incorporating a hashbang into a JavaScript file that is executable without compromising browser compatibility

Is it possible to run code like this in both Node.js and the browser? #! /usr/local/bin/node console.log("Hello world") I have a script that I currently run locally in Node.js, but now I want to also execute it in the browser without having to modify it ...

Is it possible for you to provide both a status code and an HTML webpage?

I've been working with the express framework in node, but I'm unsure if what I'm doing is best practice. I want to send a specific status code such as res.status(200).send("Success"); when the form input matches the server, and another statu ...

Converting from Async.js parallel to Bluebird: A Step-by-Step Guide

Utilizing async.js allows me to define promises with handlers, providing polymorphism and separating results. Can this be achieved in bluebird as well? async.parallel({ cityPromises: (cb)=>{ City.find({ ...

``Is there a way to effectively assess the Angular UI-Grid cellTemplate function in the attribute value only when it is displayed

Utilizing angularjs and ui-grid with a custom cellTemplate, each cell contains an object referred to as COL_FIELD. This object is passed to a function that generates an image data URI used in the src attribute of the cellTemplate to display images within e ...

Using jQuery to manipulate the radio button input's alternate content in HTML attributes

How can I use Jquery Attr.Radio Button click to write to the div with id #RadioDesc? <input type="radio" desc="sample description" class="AddText"> <script type="text/javascript"> $( document ).ready( function() { $("radio").click ...

Differences in characteristics of Javascript and Python

As I tackle an exam question involving the calculation of delta for put and call options using the Black and Scholes formula, I stumbled upon a helpful website . Upon inspecting their code, I discovered this specific function: getDelta: function(spot, str ...

Ways to retrieve a variable from a separate TypeScript document

A scenario arises where a TypeScript script contains a variable called enlightenFilters$: import { Component, Input, OnInit } from "@angular/core"; import { ConfigType, LisaConfig } from "app/enrichment/models/lisa/configuration.model"; ...

Accessing the page directly in a Nuxt SPA is not permitted

I'm currently working with Nuxt version 2.3.4. In my project, I am utilizing vue-apollo to fetch data for a file named pages/_.vue, which dynamically manages content. As indicated on this documentation page, this is the recommended approach for handli ...

The MUI Autocomplete filterOptions is not effectively filtering out all options as expected

Hey there! I'm facing an unusual situation with my Autocomplete feature, which has been heavily customized to meet certain restrictions and requirements. The issue I am encountering is related to filtering. Despite successfully filtering the results ...