Transforming text to numbers in JSON with JavaScript

Below is the JSON data that I have:

{
  "Title": "Test",
  "StartDate": {
    "Month": "3",
    "Year": "1973"
  },
  "EndDate": {
    "Month": "4",
    "Year": "1974"
  }
}

I am looking to extract the Month and Year values from both StartDate and EndDate fields without quotes, as shown below:

{
  "Title": "Test",
  "StartDate": {
    "Month": 3,
    "Year": 1973
  },
  "EndDate": {
    "Month": 4,
    "Year": 1974
  }
}

EDIT I want to clarify that I am not generating this JSON using JSON.stringify(). The JSON is being created by a Form Builder module in Angular 2. Despite specifying the type as number, the values are still encapsulated in quotes.

Answer №1

To ensure your JSON is properly formatted, make sure to utilize the parseInt() function for converting values into integers before saving. This will eliminate any unnecessary quotes.

JSON.stringify({
    Year: parseInt( data , 10);
})

For more information, refer to this resource.

Answer №2

UPDATE

If you initially created the JSON Object in your JavaScript code, follow @Adrian Lambertz's solution. However, if you received the JSON as a String from another source and need to convert it, refer to my method :

Here's my original approach

In case you have a JSON string within your JavaScript code, here is how you can transform specific values into integers :

var data = JSON.parse(JSONStringToTransform);

// Assuming the JSON String consists of events each with Title, StartDate, and EndDate properties
for (var j = 0; j < data.length; j++) {
    // If the JSON String does not contain an array of events, adjust the logic accordingly
    data[j].StartDate.Month = parseInt(data[j].StartDate.Month);
    data[j].StartDate.Year = parseInt(data[j].StartDate.Year);
    data[j].EndDate.Month = parseInt(data[j].EndDate.Month);
    data[j].EndDate.Year = parseInt(data[j].EndDate.Year);
}

// Generate a JSON String without quotation marks around Month and Year values
var convertedJSONString = JSON.stringify(data);

Answer №3

Simply transform the text into numerical values. Feel free to customize this code snippet based on your specific object setup.

function convertToNumbers(data) {
  for (const key of ['StartMonth', 'EndYear']) {
    for (const value of ['Day', 'Hour']) {
      data[key][value] = Number(data[key][value]);
    }
  }
}

Answer №4

The order in which the data is expected may not be clear, so I will provide two versions below.

Object -> JSON (-> Object)

To convert an object to JSON and back to an object, you can use JSON.stringify along with a replacer function that converts certain keys like Month and Year into numbers.

var dataObj = { "Title": "Test", "StartDate": { "Month": "3", "Year": "1973" }, "EndDate": { "Month": "4", "Year": "1974" } },
    jsonStr = JSON.stringify(dataObj, function (k, v) {
        return ['Month', 'Year'].indexOf(k) !== -1 ? +v : v;
    }),
    parsed = JSON.parse(jsonStr);

console.log(jsonStr);
console.log(parsed);

JSON -> Object

If you want to convert JSON back to an object, you can use JSON.parse along with a reviver function that converts certain keys like Month and Year into numbers.

var jsonStr = '{ "Title": "Test", "StartDate": { "Month": "3", "Year": "1973" }, "EndDate": { "Month": "4", "Year": "1974" } }',
    parsed = JSON.parse(jsonStr, function (k, v) {
        return ['Month', 'Year'].indexOf(k) !== -1 ? +v : v;
    });

console.log(parsed);

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

Is there a way to modify the output Json during serialization on a broader scale, even if the class definitions are not modifiable?

Suppose the following: You have a collection of Java objects that need to be passed to an API You are unable or unwilling to modify the declaration of these objects Unfortunately, the API requires additional information not present in the objects For in ...

Executing a JavaScript/jQuery function on the following page

I'm currently working on developing an internal jobs management workflow and I'd like to enhance the user experience by triggering a JavaScript function when redirecting them to a new page after submitting a form. At the moment, I am adding the ...

Watchify fails to detect any modifications in the directories above

I currently have multiple apps stored in a single folder with a shared dependency. /app/app1/src/main.js /app/app2/src/main.js /app/app3/src/main.js /common/tools.js Each of these apps has its own instance of Watchify running, and any changes trigger a r ...

Experiencing an error with Angular's $resource module: encountering an issue with unknown providers while trying to

After a year of working with rails, I decided to tackle my first angular app. While I've been learning from tutorials, I'm facing some challenges now. Despite searching through various SO questions, I couldn't find a solution for this partic ...

How can I integrate both the ui-bootstrap datepicker and timepicker in an AngularJS application?

I am currently developing a web application that utilizes UI-Bootstrap's datepicker and timepicker directives. The datepicker is set up as a simple popup dialog, while the timepicker appears on the page next to the datepicker. However, I am facing ch ...

data.map` does not work as a function

I've encountered a persistent error that has me stumped. Here's the code snippet: JSON {"inventory": [ { "item_id" : "123", "item_data" : { "image_id" : "1234", "description" : "foo", "lin ...

Can Bootstrap buttons be manipulated to mimic checkbox behavior effectively?

Looking to implement the data-toggle feature of Bootstrap for enabling users to choose their privilege level. I created a simple demonstration on JSFiddle, where the expected values are: None: 0 User: 1 Administrator: 2 User + Administrator = 3 The iss ...

Issue with React select dropdown not properly updating selected value

My website has a form with the default value of ethExperienceLevel set to "BEGINNER". I have a function that is supposed to update the selected state when switching between options in a dropdown list, triggered by an onChange handler. However, I noticed ...

A method that sorts an array of objects based on their properties

I am currently working with two specific objects: clinics: [ { id: 1, name: 'New Hampshire Veterinarian Clinic', plans: [ 'handle123', 'handle567', ] }, { ...

The execution of 'observe' on 'MutationObserver' failed because parameter 1 is not the correct type of 'Node'. Ensure to use select2() instead

Attempting to implement select2 for dynamically loaded data via ajax, I am encountering the error mentioned above. What could be the issue? Below is the code snippet in question: $(document).on('change', '[name="country"]', fu ...

Extracting various data points from a JSON document

I am dealing with a JSON file containing multiple elements like the following: { "code" : "hfuiew89", "type" : "location", "coordinates" : [ { "lat" : 40.9861, "lon" : 29.1046, "index" : 1 }, { "lat" : 40.9976, "lon" : 29.1153, "index" : 2 } ...

What is the method for configuring a dynamic default download folder in ChromeDriver using a JSON file?

I implemented my own method to launch the driver, where I used the following code to set the default download directory: DesiredCapabilities caps = DesiredCapabilities.chrome(); ChromeOptions co = new ChromeOptions(); HashMap<String, Object> chromePr ...

When React-select is toggled, it displays the keyboard

While using react-select ^1.2.1, I have come across a strange issue. Whenever I toggle the drop-down in mobile view, the keyboard pops up unexpectedly as shown in this screenshot https://i.stack.imgur.com/mkZDZ.png The component code is as follows: rende ...

Retrieve data from a server using an Ajax GET request to access information stored within an HTML

Seeking guidance on implementing a jQuery GET request for retrieving specific information from a page structured similar to the following: <tr class='tr'> <td class='example1'> <span> Information I possess ...

Elusive Essence: Mysterious Origins of the

Beginner in the world of Ionic and Angular. I am attempting to create a test app and incorporating the factory function. I obtained the design from Ionic Creator and now trying to add my code to it. Here is my controller file. angular.module('app.c ...

Tips for utilizing the if statement within ng-repeat in Angular version 1.0.8

My version of angular is 1.0.8-stable My main goal is to arrange data in rows of 3. This is the desired structure for my HTML: <div class="table-row"> <div class="item">item1</div> <div class="item">item2</div> ...

What is the process for duplicating a set of elements within an svg file and displaying the duplicate at a specific location?

SVG <svg width="200" height="200"> <g id="group"> <rect x="10" y="10" width="50" height="20" fill="teal"></rect> <circle cx=" ...

Quirks in TailwindCSS template literals behavior

Looking at this specific component: const SaleBadge = ({ textContent, badgeColor }) => { return ( <Badge className={`bg-${badgeColor}-200 hover:bg-${badgeColor}-300 animate-pulse align-middle ml-2`} variant="secondary"><Pe ...

Discovering the power of Next.js Dynamic Import for handling multiple exportsI hope this

When it comes to dynamic imports, Next.js suggests using the following syntax: const DynamicComponent = dynamic(() => import('../components/hello')) However, I prefer to import all exports from a file like this: import * as SectionComponents ...

There seems to be an issue with the cookie functionality as it is not

My code for setting and getting Cookies is as follows: $.setCookie = function (c_name, value, exdays) { var exdate = new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + e ...