A method to transform all JSON values into strings without needing to loop through each one

I need to convert all values in a JSON object into strings. These values could be numbers, booleans, undefined, or null.

{
    "obj1": [{
        "n1": "n",
        "n2": 1,
        "n3": true
    },
    {
        "n1": "n",
        "n2": 1,
        "n3": null
    }]
}

The desired outcome is for all values to be converted to string.

Example:

{
    "obj1": [{
        "n1": "n",
        "n2": "1",
        "n3": "true"
    },
    {
        "n1": "n",
        "n2": "1",
        "n3": "null"
    }]
}

We can achieve this by iterating through the JSON object, but I am wondering if there is a simpler method to accomplish this task.

Answer №1

To transform values into a string or keep them as is, you can utilize JSON.stringify along with a replacer function which verifies if the value is a number.

var object = { obj1: [{ n1: "n", n2: 1, n3: true }, { n1: "n", n2: 1, n3: null }] },
    json = JSON.stringify(object, (k, v) => v && typeof v === 'object' ? v : '' + v);

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

Answer №2

To achieve this, you can utilize the Json.stringify() method.

For instance:

var data = { info1: [{ num1: "n", num2: 1, num3: true }, { num1: "n", num2: 1, num3: null }] };

To view the output, simply employ the Json.stringify() method:

console.log(JSON.stringify(data, (key, value) => value ? value.toString() : value));

Answer №3

const myObject = {
    "item1": [{
        "value1": "v",
        "value2": 1,
        "value3": true
    }, {
        "value1": "v",
        "value2": 1,
        "value3": null
    }]
};
const data = JSON.stringify(myObject)
const updatedObject = data.replace(/:([^"[{][0-9A-Za-z]*)([,\]\}]?)/g, ':\"$1\"$2')
console.log(updatedObject);
/*
{"item1":[{"value1":"v","value2":"1","value3":"true"},{"value1":"v","value2":"1","value3":"null"}]}
*/

// Let's format it for better readability
console.log(JSON.stringify(JSON.parse(updatedObject), null, 2));
/*
{
  "item1": [
    {
      "value1": "v",
      "value2": "1",
      "value3": "true"
    },
    {
      "value1": "v",
      "value2": "1",
      "value3": "null"
    }
  ]
}
*/

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

Retrieving the authenticated user post logging in through Firebase

After a user signs up, I want to send a verification email. I've written the code for it, but I'm facing an issue where trying to access the current user with Firebase in React Native always returns null. How can I resolve this? Below is the sig ...

The Quivering Quandaries of Implementing Jquery Accordions

For a demonstration of the issue, please visit http://jsbin.com/omuqo. Upon opening a panel by clicking on the handle, there is a slight jitter in the panels below during the animation. In the provided demo, all panels should remain completely still as t ...

A mistake has been identified: The object could potentially be 'null'. TS2531 for window.document

This is my first time integrating TypeScript into my project. When attempting to access something using window.document.getElementById(), I keep encountering the error: Type error: Object is possibly 'null'. TS2531 I've looked online for ...

Reasons Child Components in React Native & Redux Are Not Re-rendered with Every State Update

Within my React Native and Redux setup, I have a <NavigationCardStack/> component serving as the root. Whenever the state is updated, the redux-logger correctly displays the new state. However, after a state change, the child component fails to log ...

"Error in Python dpath.util.get when Empty String Keys are Encountered

After successfully reading a simple JSON text file and parsing it into a dict, I encountered an unexpected error when trying to retrieve specific elements using the dpath package. >>> data.keys() dict_keys(['metadata', 'value' ...

What is the process for printing with JQuery?

I have nested divs with dynamically generated images in my HTML code. My problem is that when I click the print button, I want the corresponding image to be printed. <div id="outputTemp" style="display:none"> <div id="rightoutputimgae"> <di ...

Request made to Ajax fetching complete webpage content

I have a page full of random tips at http://www.javaexperience.com/tips To display these tips on other pages of the website, I am using an ajax call to add the content returned by the call to a specific div's HTML. The code for the div is: <div ...

What is the process for retrieving and showcasing the authorized user's order from the Firebase Realtime Database in an Angular application using AngularFire?

I have implemented the following function to insert orders into the database, and it is working perfectly: async createPackage(){ const itemsRef = this.afDatabase.database.ref(`delivery orders/${this.uid}`); const userId = itemsRef.push({packageName: this ...

Invoke a web service with jQuery through Ajax requests

I am attempting to implement an Autocomplete feature for a search field but I am facing issues with the code provided below. The problem is that the web method is not triggering when the Autocomplete function runs. What could be causing this issue? Below ...

Enhance an existing JsonObject in javax.json by introducing a fresh JsonNumber

When it comes to adding properties to an existing instance of JsonObject, dealing with boolean values is simple: JsonObject jo = ....; jo.put("booleanProperty", JsonValue.TRUE); However, the process becomes more challenging when trying to add a JsonNumbe ...

Exploring Angular $resource with a playful twist

Is there a recommended method for mocking the $resource object? I've looked online, but all my attempts ended with KARMA testing. It's not what I'm looking for. I'm thinking of creating a fake object so that I can easily switch betwee ...

Is it feasible to programmatically click a div button in C# using WebBrowser?

Exploring the capabilities of WebBrowser in C#, I came across a website that features a button without an ID, but rather nested within a div element. <div class="pc-image-info-box-button-btn-text pc-cursor"><i class="fa fa-heart" aria-hidden="tru ...

Show content based on information from an array using JavaScript

I am currently working on developing a user-friendly step-by-step form using AngularJS and UI-router to navigate through different sections. The data collected from each form is stored in a JavaScript array, and I am trying to dynamically show or hide a di ...

Sending a HttpDelete request with a JSON body on Android Application

Is there a way to call a web service and delete data using HttpDelete? The service requires a JSON object as a parameter. While I have experience with HttpPost and using SetEntity, it seems that method is not available for HttpDelete. The call looks like ...

The error message "Seed is not defined" is raised when the program attempts to

I'm currently diving into fullstack vue and I'm perplexed by the error occurring in this particular scenario. window.Seed = (function () { const submissions = [ { id: 1, title: 'Yellow Pail', ...

Update the value in a nested object array by cross-referencing it with a second nested object array and inserting the object into the specified

I have a large array of objects with over 10,000 records. Each object contains an array in a specific key value, which needs to be iterated and compared with another array of objects. If there is a match, I want to replace that value with the corresponding ...

Tips for ensuring a watcher only runs once in each digest cycle, regardless of how many times the property is modified

I am facing an issue with my function $scope.render() that relies on the value of $scope.myProperty to render a chart. Whenever myProperty changes during a digest cycle, I need to ensure that $scope.render() is called only once at the end of the digest cyc ...

The identity becomes blurred once information is transmitted to a modal

I'm having an issue with a recipe table that belongs to a specific user. When the pencil icon on each row is clicked, a modal should display, showing the recipe details and allowing the user to edit and save the updated version. However, I've enc ...

What causes Spyscroll to be impacted by Collapse in Bootstrap 5?

I'm utilizing bootstrap 5 as my CSS framework and currently working on a significant section. Therefore, I chose to structure it with one row containing four columns, hiding the others using Bootstrap's collapse feature. However, because this is ...

Creating a single row on the Wordpress options page with a colspan in the first row

On my WordPress options page, I am utilizing the Fluent Framework to create fields. This framework is quite similar to Meta Box, as both make use of the do_settings_fields function to generate code like the following: <table class="form-table"> < ...