SGN SGN - 2 months ago 8
JSON Question

Converting strings to intergers in JSON using JavaScript

I have the following json

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


I want
Month
and
Year
values from
StartDate
and
EndDate
to be without quotes, like this:

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


EDIT
I'm not creating the json, with JSON.stringify(). My JSON is created by Form Builder module from Angular 2, despite the fact that I'm setting it's type to number, after I change the value, the value gets quotes.

Answer

EDIT

If you made that JSON Object earlier in your JavaScript code, go for @Adrian Lambertz's answer. If you got that JSON as a String from somewhere else and want to convert it, read my answer :

My original answer

Say you got this JSON as a string in your JavaScript code, you could convert the desired values to integers like this :

var events = JSON.parse(JSONStringYouWantToConvert);

// if the JSON String is an array of events that all have a Title, a StartDate and an EndDate
for (var i = 0; i < events.length; i++) {
    // else, forget about the loop and the [i] index, the concept remains the same
    events[i].StartDate.Month = parseInt(events[i].StartDate.Month);
    events[i].StartDate.Year = parseInt(events[i].StartDate.Year);
    events[i].EndDate.Month = parseInt(events[i].EndDate.Month);
    events[i].EndDate.Year = parseInt(events[i].EndDate.Year);
}

// make a JSON String that wont have the quotes around the Month and Year numbers
var JSONStringConverted = JSON.stringify(events);
Comments