Issue with Backbone 1.2 throwing incorrect JSON during model saving?

I am new to working with backbone and I have been attempting to save my model into a JSON file.

Everything seems to be working fine, until I try to read the JSON output by my backbone application. Upon using Jsonlint, I discovered that my JSON is not valid. Here are some specific details:

Here's how my Model (index.htm) looks like:

//--------------
// Model
//--------------
app.Todo = Backbone.Model.extend({
  defaults: {
    firstName:'',
    lastName:'',
    address:'',
    occupation:'',
    email:'',
    idNumber:'',
    phoneNumber:''

},

This is the function responsible for saving:

createTodoOnEnter: function(e){

app.todoList.create(this.newAttributes());

// clean input box
      firstName: this.firstName.val('');
      lastName: this.lastName.val('');
      address: this.address.val('');
      occupation: this.occupation.val('');
      email: this.email.val('');
      idNumber: this.idNumber.val('');
      phoneNumber: this.phoneNumber.val('');

},
newAttributes: function(){


return {

  firstName: this.firstName.val().trim(),
  lastName: this.lastName.val().trim(),
  address: this.address.val().trim(),
  occupation: this.occupation.val().trim(),
  email: this.email.val().trim(),
  idNumber: this.idNumber.val().trim(),
  phoneNumber: this.phoneNumber.val().trim()

}

}

The resulting JSON when saved is as follows:

{
firstName: "ramy",
lastName: "dabbabi",
address: "50 rue Fadhel ben achour",
occupation: "Developer",
email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cdbfaca0b48daaa0aca4e3aea2a0">[email protected]</a>",
idNumber: 09008585,
phoneNumber: 789456123
}

You may notice that the attributes (firstName, lastName, etc.) are missing double quotes which is causing the JSON to be invalid.

Is there a way to fix this issue? Is there a built-in function in backbone that allows me to define the JSON format?

Can I customize the JSON output created by the this.model.create function?

Answer №1

It seems like you might be utilizing the toJSON method. Upon reviewing the documentation, you'll notice that it doesn't actually provide a JSON string as output.

The toJSON method returns a shallow copy of the model's attributes for JSON stringification. This can be helpful for persistence, serialization, or any pre-processing before sending data to the server. Despite its name, it does not directly return a JSON string — this is due to how the JavaScript API for JSON.stringify functions.

If needed, you can convert the outcome by using `JSON.stringify(model.toJSON())`.

Furthermore, it is possible to customize the backbone methods if required.

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

Infinite scrolling with Jquery: Loading dynamic content seamlessly from external websites

Hey there! I recently started using this cool jQuery plugin called jquery-endless-scroll. Here's a snippet of my code: $(function() { $('#list').endlessScroll({ pagesToKeep: 10, fireOnce: false, insertBefore: "#list div:first ...

The state remains unaltered within the confines of the useState hook and useEffect function

I encountered a similar issue to the one discussed in this particular question The code provided was extensive, so I created a simplified version of the problem. (I apologize if there was an error in my approach) Essentially, I have a main component and ...

Is there a way to exclude certain URLs from the service worker scope in a create react app, without the need to eject from the project?

Is there a way to remove certain URLs from a service worker scope in create-react-app without needing to eject? The service worker is automatically generated, and it seems impossible to modify this behavior without undergoing the ejection process. ...

Navigating through an array in JSON using Swift

https://i.sstatic.net/Enm2u.png I have created a structure to decode the data obtained from JSON. https://i.sstatic.net/LZ8FC.png In the main code section, I access the array result and retrieve the title to print it out. The result array contains 14 item ...

The attribute @Validation.For("orderName") is not recognized

Attempting to extract the Order Form from the Bakery Template for use on my website has resulted in an error in the code: "@Validation.For("orderName")" attribute is unknown. <div class="fieldcontainer" data-role="fieldcontain"> ...

Node.js is raising an error because it cannot locate the specified module, even though the path

Currently in the process of developing my own npm package, I decided to create a separate project for testing purposes. This package is being built in typescript and consists of a main file along with several additional module files. In the main file, I ha ...

Dynamic routing with ngIf in Angular 2's router system

Is there a way to use *ngIf with dynamic router in Angular? Let's say I have a top navigation component with a back button, and I only want the back button to be visible on the route 'item/:id'. I tried using *ngIf="router.url == '/ite ...

"JavaScript that doesn't rely on a specific browser

Why does this code behave differently across browsers? What modifications are needed to ensure consistent behavior in all of them? In Firefox, it functions correctly, using the URL /some/path/?searchedText=sometext. However, in IE, nothing happens when cli ...

Update the variable values in the Onclick function

I am trying to modify the onClick function attached to a button. My goal is to change the function var from 'create' to 'update' when the page loads and also through other functions. I attempted the code below but it did not work as exp ...

The Angular Element's emitted number transforms into a string once it reaches the JavaScript event listener

Within my Angular Elements web component, I have defined and emitted events in the following way: @Input() groupId: number = -1; @Output('group_change') groupChange!: EventEmitter<number>; ... this.groupChange.emit(groupId); I integrated ...

Where can I locate the Socket.IO server within the local area network (LAN)?

I am currently in the process of developing an application that facilitates connections between devices within the same network. In my design, any device can act as a server, and I aim for clients to automatically detect the server without requiring users ...

Arranging items in Angular based on selection from the database

i have data in table: Id, word, score , score_list. score are 0.4, 0.2, -0.5, 0, -0.3 .... in score_list i have positive, negative , neutral. How can i sort data with select by score_list? This is html <select class="form-control"> <option> ...

Issue with AngularJS: error:areq Invalid Argument

<!DOCTYPE html> <html ng-app> <body data-ng-controller="SimpleController"> <div class="container"> Title: <br/> <input type="text" ng-model="title" />{{title}} <br/> ...

Unable to reach the object property while using the $.each method

Upon receiving an object from an ajax request, I am using $.each to iterate through all the appointments in the object. However, I am encountering an issue where the object appears to be undefined within the $.each loop. Here is the code snippet for my req ...

Encountering a CORS Policy Blockage Issue When Using JSON Data, but Resolving it by Changing the Header Type

I created a basic input form that updates data when information is added to it. After following a tutorial, I noticed they used application/json in the header for rendering json data within the input fields. let url = 'http://local ...

Accessing the req property beyond the route endpoints

const express = require('express'); const router = module.exports = express.Router(); const server = require("http").Server(express); const io = require("socket.io")(server); server.listen(5000); // Need a way to access user.id here router.g ...

Using the Wikipedia API to search - How to retrieve corresponding indexes of each array using forEach?

Struggling on a project for freeCodeCamp related to the Wikipedia API. Despite being able to work with the data, I'm unsure about the syntax required to achieve my goal. Here's an example of the data I am dealing with: Wikipedia API Search. In m ...

Python Tutorial: Decoding JSON Objects with Unicode Encoding

I recently stored a JSON object in a file using the repr function like so: f = open('file', 'w') f.write(repr(my_json)) f.close() After saving, I noticed that the JSON data now has leading 'u' characters denoting unicode enc ...

Implementing a specialized CSS handler for Node.JS

Currently, I have set up a Node.JS server for a new project at my workplace. As part of the project, I have created an optimizer function that removes unnecessary elements such as tabs, newlines, and comments from HTML, JavaScript, and CSS files. Strangel ...

Using the HttpPost method to send an HTTP request

Hey there, I could really use some help. For the past 15 days, I've been stuck and unable to find a solution anywhere for my issue. The code snippet below shows how I am making an HTTP request with parameters passed in JSON format. However, it seems t ...