Understanding Escaped JavaScript Syntax

Looking for help parsing a string into a JSON object and converting it to a javascript array. Here is the initial string:

"[{\"items\":\"nut\",\"sales\":6,\"prices\":10},\n {\"items\":\"bolt\",\"sales\":8,\"prices\":20},\n {\"items\":\"cam\",\"sales\":0,\"prices\":15},\n {\"items\":\"cog\",\"sales\":3,\"prices\":20}]"

After removing the newline character, we get:

"{\"items\":\"nut\",\"sales\":6,\"prices\":10}, {\"items\":\"bolt\",\"sales\":8,\"prices\":20}, {\"items\":\"cam\",\"sales\":0,\"prices\":15}, {\"items\":\"cog\",\"sales\":3,\"prices\":20}"

I attempted the following code:

   dd = "[{\"items\":\"nut\",\"sales\":6,\"prices\":10},\n {\"items\":\"bolt\",\"sales\":8,\"prices\":20},\n {\"items\":\"cam\",\"sales\":0,\"prices\":15},\n {\"items\":\"cog\",\"sales\":3,\"prices\":20}]";
   dd = dd.replace(/\\n/g, '');
   dd = dd.replace(/[\[\]']+/g,'');
   console.log(JSON.parse(dd));
   dd= JSON.parse(dd));

However, the JSON doesn't parse correctly as dd.items returns null.

Answer №1

However, the json is not being parsed correctly as dd.items returns null for some unknown reason.

Do not bother removing newline characters (\n) from the string, just use JSON.parse directly.

var dd = JSON.parse( "[{\"items\":\"nut\",\"sales\":6,\"prices\":10},\n {\"items\":\"bolt\",\"sales\":8,\"prices\":20},\n {\"items\":\"cam\",\"sales\":0,\"prices\":15},\n {\"items\":\"cog\",\"sales\":3,\"prices\":20}]" );
console.log(dd);

Remember that dd is an array, so you must iterate through dd to access the items property.

dd.forEach( s => console.log(s.items) );

Answer №2

const data = "[{\"product\":\"apple\",\"quantity\":5,\"price\":2},\n {\"product\":\"banana\",\"quantity\":8,\"price\":1.5},\n {\"product\":\"orange\",\"quantity\":3,\"price\":2},\n {\"product\":\"grape\",\"quantity\":6,\"price\":3}]";
const parsedData = data.substr(1, data.length - 2).split(',\n').map(JSON.parse);
console.log(parsedData);

Answer №3

To get rid of this, simply execute the following: JSON.parse(dd);

Answer №4

let info="[{'product':'apple','quantity':5,'price':2},\n {'product':'banana','quantity':10,'price':1},\n {'product':'orange','quantity':7,'price':3}]";

//Use JSON parse to convert the string into a JSON array of objects without modifying the original string

console.log(JSON.parse(info));

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 value of type 'X' cannot be assigned to type 'Y' or 'undefined'

In my code, there is a component that requires a prop with an enum value: export enum AType { some = "SOME", word = "WORD", } const MyComponent = (arg: AType) => {} When I try calling this component like so: <MyComponent ar ...

What is causing the beforeUpdate hook in Sequelize to fail?

I have a user model with 2 hooks that I am working on. User.beforeCreate(setSaltAndPass) User.beforeUpdate(setSaltAndPass) The first hook works perfectly fine, but the beforeUpdate hook is not triggering as expected. As per the documentation, there should ...

Using a variable as a location URL: A step-by-step guide

Hello everyone! Can anyone guide me on how to assign the file URL location to a variable in JavaScript? NgMap.getMap().then(function (map) { $scope.map = map; var myParser = new geoXML3.parser({ map: map }); ...

Is there a way to access the name of a generic type T class in TypeScript?

I'm currently working on incorporating the Service Locator pattern into my TypeScript project. Below is the snippet of my code: //due to only partial knowledge of TypeScript private static serviceMap: Map<string, any>; public static get& ...

Combining two collections in MongoDB and calculating the total number of documents

I'm seeking guidance on working with mongodb and node.js. I currently have a collection called PIZZA { title: "bacon" } { title: "pepperoni" } as well as another collection named ORDERS { orderid: 1, pizza: "bacon" } { orderid: 2, pizza: "pepperoni ...

What is the reason for sending back an array with no elements in AJAX

I am facing a perplexing issue where my function is returning an empty array when it should contain values. This has me scratching my head, as initially the array 'storearray1' does contain values, but upon subsequent usage, it appears empty. I&a ...

Callback function in JSON upon completion of file upload

I am facing an issue with uploading a file through json/ajax as the file does not seem to be uploaded successfully. Only the name of the file appears in the console output. Here is my HTML code: <form action="/cgi-bin/upload.cgi" method="post" enctype ...

Preserve and recover the dynamic form value following an AJAX update

Looking for a solution for saving and restoring user comments on dynamically created form fields in a page where users can comment on posts. How can we save and restore the typed comments before an ajax refreshes the div holding all the post and comments? ...

Using node-native to authenticate in MongoDB is a surefire way to ensure the

I'm currently facing an issue while attempting to save a document in MongoDB within my Nodejitsu/MongoHQ application. Everything works perfectly locally, but the MongoHQ database requires authentication and it fails even with the correct user/password ...

Memory Exhausted: MongoDB and JavaScript running out of memory

Dealing with a massive amount of data in the telemetry table is proving to be a challenge. I keep encountering the dreaded "JavaScript heap out of memory" error. How can I tackle this issue? const connectionUrl = `mongodb://${userName}:${pwd}@${host}:${ ...

Having issues with my JavaScript timer - seeking assistance in troubleshooting the problem

Trying to set a timer for my little game, but facing some difficulties. The timer causes the balance to randomly increase from 0 to 13000 + some extra amount. <script> var coins = 0; var speed = 1; </script> <center> <h4> ...

Insert a fresh row into the current table

Is it possible to add a new row to an existing table in SAP UI5? Below is the code snippet: onInit: function() { var oModel = new sap.ui.model.json.JSONModel("Model/Clothing.json"); this.getView().setModel(oModel); var table = this.getView(). ...

How can I create a Discord bot command that ignores case sensitivity?

I wrote a custom "roleinfo" command for my Discord bot, but I'm struggling to make the role search case insensitive. Here is the code snippet: const Discord = require("discord.js"); module.exports.run = async (bot, message, args) => { //Me ...

Encountering a compile error with a Next.js React project that cannot be resolved

Encountered an issue while refreshing my project with the command "npm run dev" and reloading the site locally. The console displays "Compiled /not-found" and the site fails to load completely. In addition, none of the elements animated via framer motion ...

The $POST method is failing to update the information

I've encountered an issue with my script that I can't seem to figure out. After numerous tests, it seems like the main problem lies within the Ajax request. Interestingly, I have used the Ajax request successfully in a previous version of my scri ...

Ant design of the card

I am struggling to make the image appear in full width within the ant design card component. import React, { useState, useEffect } from 'react'; import uno from '../images/dualComida.jpg' import { Button, Space, Typography, ...

Exploring the possibilities of manipulating the query string with Vue router in vue.js

I've been working on a Vue.js app that includes a tagging feature. I'm looking to implement URL parameters like where users can add tag_ids by interacting with the UI. Although I've successfully managed to update the tag_ids within the app ...

When the user clicks the back button in AngularJS

After searching extensively, I have yet to find a straightforward solution to my issue. The problem lies in a search/filter field that filters the page based on user input. While this filter works efficiently, it clears whenever a navigation item is clicke ...

What could be preventing my component from importing properly in App.vue?

I am attempting to display a pulse loader while the page is loading. However, I encountered two errors in the code below. App.vue <template> <div id="app"> <div id="nav"> <router-link to='/'><div v-if="$ro ...

Unable to dynamically translate special characters using npm latinize

When translating German special characters to English using latinize, the module only works when strings are passed within single or double quotes. However, it does not work when storing them inside a variable. import latinize from 'latinize'; ...