Convert JavaScript objects to strings with JSON strings already included as values

Although this question may seem like a duplicate, I have not been able to find the answer. My issue is with stringifying a JavaScript object that contains JSON strings as values.

Here is an example:

var obj = {id:1, options:"{\"code\":3,\"type\":\"AES\"}"};

As you can see, the value for key 'options' is a JSON string. I am looking for a way to stringify the object 'obj' without double stringifying the inner JSON string.

Is there a more elegant solution for this problem, rather than parsing each value with JSON.stringify and then stringifying the object?

Answer №1

In cases where you are unsure which values in an object are JSON strings, you can utilize the replacer function parameter in the JSON.stringify method to identify and parse them accordingly. The example below demonstrates how each string is attempted to be parsed within a try-catch block for efficient handling of nested properties.

var data = {id:1, info:"{\"name\":\"John\",\"age\":30}"};

function checkValue(key,value){
if(typeof value === 'string'){
try{return JSON.parse(value);}catch(error){} // attempting to parse as JSON
}
return value;
}

var result = JSON.stringify(data,checkValue); // using custom replacer function

console.log('original output:', JSON.stringify(data))
console.log('with replacer function:', result);

Answer №2

Sorry, it is not possible to perform that action.
If the string was not encoded, JSON.parse will not produce the correct output.

An efficient approach is to utilize JSON for obj.options and convert it to a string when necessary.

Answer №3

If you find yourself in this situation, the first step is to convert options into a JSONObject. You have two different methods to accomplish this:

Method 1:

var data = {id:1, options:"{\"code\":3,\"type\":\"AES\"}"};
data.options  = JSON.parse(data.options);
console.log(JSON.stringify(data));

Method 2:

var data = {id:1, options:"{\"code\":3,\"type\":\"AES\"}"};

var result = JSON.stringify(data, function(key, value) {
    if (key === "options"){
            return JSON.parse(value);
        }else{
            return value;
        }
});

console.log(result);

By following these steps, you will only need to stringify the options once.

Answer №4

Here is how you can achieve it

let data = {id:1, info:"{\"value\":7,\"mode\":\"encrypt\"}"};

let information  = JSON.parse(data.info);

data.info = information;

console.log(data);

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

Discover how to achieve the detail page view in Vue Js by clicking on an input field

I'm a beginner with Vuejs and I'm trying to display the detail page view when I click on an input field. <div class="form-group row"> <label for="name" class="col-sm-2 col-form-label">Name</label> ...

Changing the background color of the dropdown button in Vue Bootstrap: A step-by-step guide

I've been struggling to modify the background color of a dropdown button, but no method seems to work. I've attempted changing it by using ID, removing its class and applying a new one, and even using !important to override the styles, but the ba ...

Enhancing Angular with Plotly: Implementing click events on bar chart legends

I'm currently working on implementing color pickers for my plotly-plot charts within an Angular template. I am looking to add a function that triggers when the chart legend is clicked. How can I achieve this and get a click event for the chart legends ...

While working on a JSON project in Xcode, I encountered an error in the first part of my sample

I encountered the error below: Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Unrecognised leading character\" UserInfo=0x6a2b1a0 {NSLocalizedDescription=Unrecognised leading character} Could you kindly explain the meaning of this error ...

Change a CSV string into a JSON array and assign it to a variable

I am working with JSON data that looks like this: [ { "Title": "PAGE A", "Users": "USRA" }, { "Title": "PAGE B", "Users": "USRA,USRB" } ] What is the most efficient method to convert the fields containing " ...

Receiving null value with Web API POST using [FromBody]

Below is the code for my WebAPI in C#: [Route("")] [HttpPost] public void SaveTestRun([FromBody] object data) { inputResultsToDatabase(data); } This is the ajax request I am making: sendTestData() { t ...

Replacing values in an HTML file with MySql query results

----- Problem solved, solution below ----- In my HTML file, I have a dropdown menu for various courses listed as follows: <ul> <li class="dropbtn" id="1"> <a href="">first</a> <ul class="dropdown-content"> ...

Guide for Sending a Textnode from One Page to a Different Page within a Specific Id Element through PHP

firstpage.html : <body> <?php $text = $_POST['text']; ?> <p style = "color:red; " id = "getext"><?php echo $text; ?></p> </body> secondpage.php : <body> <?php $text = $_POST['text']; ?> ...

Dealing with unique constraint violation in Mongodb when using insertMany

Currently, I'm in the process of working on a project that involves using node.js and mongodb version 5. In my collection, I have implemented a unique index for the Parcel property. However, during testing, an error is triggered: MongoBulkWriteError: ...

If a span element is present, apply a specific class to the corresponding

I am working with a dynamic list of links retrieved through AJAX. After parsing the links and appending them to a div, I have encountered an issue where some 'a' elements are followed by a 'span' that needs to be considered. Here is th ...

Setting a default value for Autocomplete in MaterialUI and React.js

Is there a way to set a default value for an Autocomplete TextField component from Material UI in React.js? I want to load a pre-populated value from the user's profile that can then be changed by selecting another option from a list. Check out my co ...

I am utilizing client-side JS to send a large number of requests. What methods can I implement to enable my server to cache this content

Here's a bit of an unusual question from someone who is new to this - I have client-side JavaScript that is making API calls using the getJSON method. Since the content doesn't change frequently, I would like to store the results on my server an ...

Display the source code of an HTML element when clicked

Is there a way to show the source code of an element on a webpage in a text box when that specific element is clicked? I am wondering if it is feasible to retrieve the source code of an element upon clicking (utilizing the onClick property), and subseque ...

Aurelia validator fails to refresh user interface

Despite the aurelia-validator plugin working correctly for form submission and validation, with all properties updating properly, the UI does not reflect any changes. There is no red outline around incorrect properties or error messages displayed. I have r ...

Exploring the Integration of Material UI DatePicker with Firestore in ReactJS: Converting Firestore Timestamps to Date Format

The database is correctly recording the date, however, when displayed, the DatePicker does not recognize the date from the database as it is in timestamp format (seconds and nanoseconds). <DatePicker margin="normal" label="Data do pedido" ...

You will still find the information added with JQuery append() even after performing a hard refresh

After making an Ajax call using JQuery and appending the returned information to a div with div.append(), I encountered a strange issue. Despite trying multiple hard refreshes in various browsers, the appended information from the previous call remained vi ...

Having trouble getting my list items to display on individual lines within the foreach loop. It just doesn't seem to be working as expected

In the event listener, I need to ensure that my list items within the forEach loop are not displaying on separate lines. This issue is causing a problem in a lengthy section of code. The goal is to update questions when an answer is clicked from a list. B ...

Understanding the Variable Scope in Event Listeners and Asynchronous AJAX Functions

Here's a question that might seem simple to some, but I'm not sure. So, when you register an event listener within an asynchronous function, one would think that all values within that function would be inaccessible once the function has complete ...

JavaScript, JQuery, and the Observer Design Pattern

Currently, I am in the process of developing a third-party application specifically for certain websites using Jquery. Lately, I have incorporated rx.Observable into my project. However, grasping the utilization of this new JS library has proven to be qui ...

Can an entire application built with a combination of PHP, JavaScript, and HTML be successfully converted to Angular 7?

After creating a complex application that heavily relies on JavaScript, PHP, HTML, and numerous AJAX calls, I am considering migrating the entire codebase to Angular 7. Is it feasible to achieve this transition without requiring a complete rewrite in Ang ...