What is the process for converting a string literal into raw JSON and then storing it?

When trying to edit object values using a text input element and JSON.stringify(txt, null, 2), everything seems fine initially. However, after submitting the input, I end up with unwanted characters like "/n" and "\" within the string literal. Despite attempting regex and string.replace() methods to remove them, my output still contains these characters:

"publisher": "[{\"name\":[\"scripps re\"],\"url\":[\"url.com\"]}]",

Even using JSON.parse(txt) logs correctly, but the undesirable line breaks and backslashes persist.

QUERY:

Is there a method to convert the edited text from the input element into valid JSON without any string literal marks?

I'm working with:

VueJS, JS.

Binding the value of the input field in this manner works as expected:

 inputVal = JSON.stringify(object[keyname])

The problem arises when assigning the newly edited text:

 Vue.set(object, keyname, newValue)

The newValue always includes unnecessary /n's and \'s.

Attempts made:

Vue.set(object, keyname, newValue.replace('/n'g,""))

Vue.set(object, keyname, JSON.parse(newValue))


{
  "publisher": "[{\"name\":[\"scripps re\"],\"url\":[\"url.com\"]}]",
  "license": {
  "text": "CC BY-NC 4.0",
  "url": "http://creativecommons.org/licenses/by-nc/4.0/",
  "description": "Attribution-NonCommercial 4.0 International"
}

How can I effectively update the value of 'license', for example, using a textarea input and preserve valid JSON format?

The desired result should be (formatted or not, just without any line break marks):

{
  "publisher": "[{"name":["scripps re"],"url":["url.com"]}]",
  "license": {
  "text": "CC BY-NC 4.0",
  "url": "http://creativecommons.org/licenses/by-nc/4.0/",
  "description": "Attribution-NonCommercial 4.0 International"
}

Answer №1

The regular expression must be adjusted -

Vue.set(object,keyname,newValue.replace('/ng',""))

s = "[{\"name\":[\"scripps re\"],\"url\":[\"url.com\"]}]".replace('/ng', "");
console.log(s);

Additionally, you have the option to utilize unescape()

console.log(unescape( "[\n {\n \"identifier\": [\n \"IDEN\"\n ],\n \"institute\": [\n \"fds\"\n ],\n \"agency\": [\n \"fds\"\n ]\n }\n]" ));

Nonetheless, according to the latest(August 2019) MDN documentation, it is recommended to use decodeURI or decodeURIComponent instead of unescape

Answer №2

To change all whitespace characters, utilize the /s character group in regex.

For instance, you can apply this code snippet:

$('textarea').value.replace(/\s/g, '')

Answer №3

Discovered the root cause!

I was initially checking the type of newdata before using JSON.parse to prevent errors, but it turned out that newdata was always a string and any of the solutions provided here would have sufficed. I made a modification to check the first character of the string for objects or arrays. This little tweak has significantly improved the functionality as everything is now handled appropriately.

A big thank you to everyone who contributed their insights. In theory, all your suggestions should have worked, but the issue lay in a part of the code that was never being executed.

if (newdata.value[0]==="{" || newdata.value[0]==="[") {
    Vue.set(self.meta,keyname.value,JSON.parse(newdata.value) )
} else {
    Vue.set(self.meta,keyname.value,newdata.value)
}

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

Converting the PHP encoded Postgresql query result into a stringified array

I have a SQL query that transforms the result into JSON format. SELECT 'FeatureCollection' As type, array_to_json(array_agg(f)) As features FROM ( SELECT 'Feature' As type, ST_AsGeoJSON(geom)::json As geometry, ro ...

"Step-by-step guide on populating a select box with data from the scope

Hey everyone, I'm new to using Angular and hoping for some help with a simple question. I've created a form (simplified version below) that I want users to see a live preview as they fill it out. Everything was going smoothly with regular field ...

How to designate the specific container to be updated in the XMLHTTP JSON code within a Joomla website?

Below are some functions that were created by a former developer who is no longer with the company. These functions query a database and return JSON code to update the inner HTML of a specific div. I have now been tasked with setting up a typeahead search ...

Ways to verify a correct email address using ReactJS

I'm currently working on a project using React.js and Next.js. I'm encountering an issue with handling the Axios response in Next.js as it's displaying "[object Object]" instead of the actual response data. How can I properly handle the resp ...

Step-by-step guide to start an AngularJs application using TypeScript

I have developed an AngularJS App using TypeScript The main app where I initialize the App: module MainApp { export class App { public static Module : ng.IModule = angular.module("mainApp", []) } } And my controller: module MainApp { exp ...

Steps for setting up node-openalpr on a Windows 10 system

While attempting to install npm i node-openalpr, an error is occurring: When using request for node-pre-gyp https download, I encounter a node-pre-gyp warning and error message. The package.json for node-openalpr is not node-pre-gyp ready, as certain pr ...

WebWorker - Error in fetching data from server using Ajax call

I've been experimenting with making AJAX calls to an ajax.htm file using web workers. The goal is to have the data continuously updated at set intervals. Although I'm not seeing any errors and the GET request appears to be successful, the data i ...

What methods can be used to identify the pattern entered by the user for data types such as `Int`, `VarChar`, `

I have a dropdown menu containing data types. There is also a text box for entering Regex patterns. If "/test/" is entered in the textbox or "Int" is selected from the dropdown, then it's an incorrect pattern. If "/[0-9]/" is entered in the ...

Responsive Alignment of Slanted Edges using CSS

I have been working on creating a responsive diagonal layout with slanted shapes (refer to the image attached). However, I'm facing a challenge with aligning the edges smoothly at different screen sizes, especially when the rows grow and the screen re ...

Integrate a scrollbar seamlessly while maintaining the website's responsiveness

I encountered an issue where I couldn't add a scrollbar while maintaining a responsive page layout. In order to include a scrollbar in my datatables, I found the code snippet: "scrollY": "200px" However, this code sets the table size to 200 pixels r ...

Can someone assist me with navigating through my SQL database?

Struggling with a script that searches multiple fields in the same table, I need it to return results even if one or three parameters are left blank. My attempts using PHP and MySql have been fruitless so far, which is why I am reaching out to the experts ...

Parsing clean data from intricate JSON structures in the R programming language

Utilizing the tidyjson package makes extracting neat data from a simple JSON effortless () However, when it comes to dealing with a more intricate nested JSON structure, applying this method becomes challenging. Specific questions like this one (how do yo ...

Encountering an issue with the removal of slides when updating JSON data for angular-flexslider

Issue: Although my JSON object is updating, the slider does not update for all resorts as expected. Sometimes it fails to update when the JSON object changes. The resorts (image collections) that do not update are throwing an error stating "cannot read pr ...

Node's getRandomValues() function is throwing an "expected Uint8Array" error

Currently, I am experimenting with the getRandomValues() function to enhance an encryption REST API that I am developing for practice. My server is using Node, which means I do not have access to a window object containing the crypto object normally housin ...

Eliminate any properties with values that exceed the specified number in size

:) I'm trying to create a function that removes properties with values greater than a specified number. I've searched through multiple resources like this question on how to remove properties from a JavaScript object and this one on removing pro ...

Adaptive Table Layout that Creates a Page-breaking Design

I have a page layout with three columns: a fixed-width left-hand navigation, a responsive content column, and a fixed-width right-hand navigation. The issue arises when the content in the middle column includes HTML tables that sometimes exceed the availab ...

Selenium Scrolling: Improving Web Scraping Efficiency with Incomplete Data Extraction

I have been attempting to extract product data from a website that utilizes JavaScript to dynamically render HTML content. Despite using Selenium, implementing scrolling functionality to reach the end of the page, and allowing time for the page to reload, ...

Leveraging the power of JavaScript Math methods to dictate the Co-ordinates of HTML Canvas .fillRect

Greetings to everyone! I have dedicated my entire evening to understanding how to implement the (Math.floor(Math.random()) function as the coordinates for the .fillRect method on an HTML canvas element. Despite searching through this website and various ...

Unveiling the Secrets of AJAX Requests with Enigmatic Strings Attached to URLs

My goal is to keep track of cricket scores on scorespro/cricket by utilizing browser AJAX requests. By analyzing the network traffic in Google Chrome, I have noticed that my browser sends out requests in this format: Whenever I click on the response withi ...

Converting Census Geocoder JSON data into an XML dataset with the help of JSON.net library in C# programming language

In the process of developing a .Net application using Visual Studio 2012, my goal is to query an address table in my SQL database and utilize the Census Geocoding API to obtain the specific MSA for each address. While I have code already set up for the dat ...