The JSON parser is still encountering issues with newlines, despite attempting to fix the problem by adding

I'm currently working on a messaging platform for a school project and facing challenges in ensuring database protection, defending against XSS attacks, and accommodating all characters, including newlines.

Everything seems to be in place, except for the issue with newlines. It's frustrating that even prefixing the newline with a backslash (\\n) doesn't resolve the problem!

https://i.sstatic.net/xzFMo.png

What should be my next step?!

Edit 1: Included the code snippet responsible for generating JSON data

string message = "[";
string uid;
for (int i = 0; i < data.Rows.Count; i++) {
    if (StringCipher.ConvertToUnixTimestamp(DateTime.Now.AddMinutes(-5)) > int.Parse(data.Rows[i][5].ToString())) {
        queryDelete = "DELETE * FROM Bubbleland WHERE MessageID = " + data.Rows[i][0] + ";";
        commandDelete = new OleDbCommand(queryDelete, connection);
        commandDelete.ExecuteNonQuery();
    } else {
        message += "{\"mid\":" + data.Rows[i][0];
        if (data.Rows[i][1].ToString() == "")
            uid = "user";
        else
            uid = data.Rows[i][1].ToString();
        message += ", \"uid\":\"" + uid;
        message += "\", \"name\": \"" + data.Rows[i][2];
        message += "\", \"color\": \"" + data.Rows[i][3];
        message += "\", \"content\": \"" + data.Rows[i][4];
        message += "\"}";
        if (i + 1 < data.Rows.Count) {
            message += ",";
        }
    }
}

message += "]";

Edit 2: Added JavaScript processing code

async function fetchMessages() {
$.ajax({
    type: "POST",
    url: "../ASPX/bubblelandFetch.aspx",
    success: function (data) {
        console.log(data);
        data = JSON.parse(data);
        var container = document.getElementById("messages-container");
        var uid;
        container.innerHTML = "";

        console.log(data);

        for (var i in data) {
            var message = '<div id="' + data[i]["mid"];
            message += '" class="message ' + data[i]["color"] + '">';
            message += '<div class="profile-container">';

            if (data[i]["uid"] == "user")
                uid = "/Media/user"
            else
                uid = "/Media/Profile/" + data[i]["uid"];

            message += '<img src="' + uid + '.png"/>';
            message += '<span>' + data[i]["name"] + '</span></div>';
            message += '<div class="content">' + data[i]["content"] + '</div>';

            container.innerHTML += message;
        }
    },

    complete: function () {
        setTimeout(fetchMessages, intevral);
    }
});
}

Answer №1

After experimenting with analyzing the string you provided, I encountered a solution and delved deeper into the reasons behind this issue.

In simple terms:
‘Single quotes “escape” single quotes’
“Double quotes ‘escape’ double quotes“

These quotes indicate that when creating a string literal with single quotes, you need to escape any single quotes with a backslash \ to make the string valid. The same applies when using double quotes, but escaping double quotes with a backslash.

Initially, I overlooked this problem despite being aware of it, even though I encounter this frequently.

I stumbled upon this informative Medium article that connects the dots, and I recommend giving it a read to brush up on using single/double quotes with string literals.

Answer №2

Unexpectedly, a non-escaped \r was causing issues with the JSON parser.

Each time you use Shift + Enter, it inserts \r\n instead of just \n. I was unaware of this behavior. Therefore, in my ASPX backend script, I substitute \r\n with <br>.

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

The @azure/search-documents JavaScript SDK allows the SearchDocumentResult to retrieve facets

Is it normal for the facets property of SearchDocumentResult to only return undefined instead of the facets involved in the query and their values? If this is the expected behavior, is there an alternative method to access the facets using the sdk? ...

Modifying the website URL in Visual Studio 2015: A Step-by-Step Guide

I've been struggling to find a solution to a challenge I've encountered in Visual Studio 2015. Currently, my website URL is set to localhost:9045, but I need to change it to a different port number and path, specifically localhost:54865/central. ...

Incorporating Javascript into a .Net MVC 3 Project

It seems like there should be a straightforward solution to my question, but I'm struggling with it. I have an animation.js file that includes dependency_1.js and dependency_2.js in an include folder. Within my animation.js file, I load these dependen ...

ngResource transformResponse guide on dealing with both successful and erroneous responses

When my API, built using expressJS, returns JSON data as a regular response, everything functions smoothly. However, when an error occurs, it returns an error code along with plain text by simply invoking res.sendStatus(401). This poses a challenge on my ...

Eliminate repeated entries in a drop-down menu and display them with commas in between

I am working with a list that contains various language combinations: German to English German to Spanish German to Chinese German to French English to Spanish English to French English to Greek English to Portuguese Does anyone have suggestions on how ...

Extract the image URL from the href attribute using Xpath

My goal is to extract all images enclosed in href attributes from the given code snippet <div class="jcarousel product-imagethumb-alt" data-jcarousel="true"> <ul> <li> <a href="https://domain/imagefull.jpg" onclick="return false;" cla ...

Disappearing Facebook share button: A common occurrence when navigating in Nuxt.js (Vue.js)

Within my nuxt.js web app, utilizing version 2.15.7, I have integrated a Facebook share button by following the instructions outlined in this comprehensive code example. Upon initial load of the application, the Facebook share button appears as expected. ...

A tool for viewing JSON files and retrieving specific data by using a key within the JSON structure

Is there an online tool available that can extract specific data from a JSON array of objects? Take this JSON array for example: { "results": [ { "createdAt": "2015-09-02T02:03:55.765Z", "name": "Clush", "score": 15, " ...

Troubleshooting: Angular input binding issue with updating

I am currently facing a challenge with connecting a list to an input object in Angular. I was expecting the updated values to reflect in the child component every time I make changes to the list, but strangely, the initial values remain unchanged on the sc ...

The concept of navigation and passing parameters in Angular.js

Attempting to customize the standard user module of MeanJS, I added a new route: state('users', { url: '/users/:username', templateUrl: 'modules/users/views/view-profile.client.view.html' }); ...

Error 414: The URL exceeds the maximum length and cannot be processed

I am currently utilizing vuejs and sending an axios request to the server in order to download a csv file. download() { var that = this //this.records = [{id: 1, name: 'Jack'}, {id: 2, name: 'Jacky'}, {id: 3, name: &apos ...

Utilize a class method within the .map function in ReactJS

In my ReactJS file below: import React, { Component } from "react"; import Topic from "./Topic"; import $ from "jquery"; import { library } from '@fortawesome/fontawesome-svg-core' import { FontAwesomeIcon } from '@fortawesome/react-fontaw ...

Is it possible for me to use ts files just like I use js files in the same manner?

So I recently stumbled upon TypeScript and found it intriguing, especially since I enjoy adding annotations in my code. The only downside is that I would have to change all my .js files to .ts files in order to fully utilize TypeScript's capabilities. ...

Filtering MUI Data Grid by array elements

I am in the process of developing a management system that utilizes three MUIDataGrids. Although only one grid is displayed at a time, users can switch between the three grids by clicking on tabs located above. The setup I have resembles the Facebook Ads ...

The implications of ASP Session security

Currently, I am exploring the idea of storing security-sensitive information (such as a user's effective permissions for our web application) in a session-resident object. This approach aims to minimize database queries when performing permission chec ...

Creating a bucket in Autodesk Forge Viewer is a straightforward process with the Forge API

I am currently facing an issue while trying to create and upload a new bucket for storing models. I keep getting a 400 Bad Request error, even though I managed to make it work in a previous project using a different method. Strangely enough, I now encounte ...

What is the best way to implement a JSON data Variable in a Flutter app without using a listview?

After researching numerous examples and similar queries, I'm still struggling to comprehend the task at hand. My aim is to extract specific data from an id within a JSON map in Flutter. The PHP response I obtain comprises 2 JSON strings (validated as ...

PHP API encountering a syntax errororEncountering

I'm in the process of developing an Android app and I require a PHP API to establish communication with an SQL Database. Encountering an error while trying to parse JSON at getJarrayFromString(); Upon logging the error, this is what was uncovered: ...

Guide to incorporating a scroll-follow effect in multiple directions

I am facing a challenge with managing an array of divs that exceed the dimensions of their container. I have set overflow to hidden on the container and used JQuery Overscroll to achieve an iPhone-like scrolling effect on the map. The problem I'm try ...

Is there a way to break this down so that I can obtain an array containing the data for each month?

My JSON structure is as follows: "meterConsumption": [ { "month": 1, "details": [ { "timestamp": "2020-01-01", ...