Search code examples
javascriptjsonobject-literal

How do I convert a JSON to an object literal?


I get data from a source in the form of a JSON. Let's say the JSON looks like this

var data = [
   {"city" : "Bangalore", "population" : "2460832"}
]

I'd be passing this data object into a kendo grid and I'll be using its out-of-the-box features to format numbers. So, I need the same JSON as an object literal that looks like this

var data = [{city : "Bangalore", population: 2460832}]

Are there any libraries, functions or simple ways to achieve this?


Solution

  • You can iterate over the Objects in the Array and modify each population property, converting its value from a string to a number with parseInt() or similar:

    var data = [
        {"city" : "Bangalore", "population" : "2460832"}
    ];
    
    data.forEach(function (entry) {
        entry.population = parseInt(entry.population, 10);
    });
    
    console.log(data[0].population);        // 2460832
    console.log(typeof data[0].population); // 'number'