1

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?

Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144
Divyanth Jayaraj
  • 950
  • 4
  • 12
  • 29
  • 1
    if it has a well known structure, just use `parseInt` for that property! – Daniel A. White May 26 '15 at 14:53
  • 3
    That "JSON" is not JSON. It's JavaScript. The only object literals you have are the same in both versions of the code. The only differences are that you have replaced a string literal with a number literal. – Quentin May 26 '15 at 14:55
  • But the end result should like an object literal so that I can reuse it anywhere I want. I don't want to apply parseInt repeatedly. – Divyanth Jayaraj May 26 '15 at 14:56
  • 1
    "Object literal" is irrelevant. You want to have your *data structure* in a certain way. The problem is that in one data structure the *values* are strings, whereas you need them to be *numbers*. It doesn't matter for the type of the value whether it's expressed as an "object literal" or what. The type of the value is wrong, period. You need to convert it, period. – deceze May 26 '15 at 14:58

2 Answers2

2

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'
Community
  • 1
  • 1
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
  • I applied this solution and it works fine. But I'm still uncomfortable with having to apply it every where I need it. I was hoping to find an out of the box solution where I can do this only once and then keep reusing the data. But thanks. I've got what I needed for now. – Divyanth Jayaraj May 26 '15 at 15:31
0

You can convert JSON into an object literal by following this idea:

(function() { 

  var json = 
   [
    {
      "id": 101,
      "title": 'title 1'
    }, 
    {
      "id": 103,
      "title": 'title 3'
    },
    {
      "id": 104,
      "title": 'title 4'
    }
  ];

  var result = {};  

  for (var key in json) {
    var json_temp = {} 
    json_temp.title = json[key].title;
    result[json[key].id] = json_temp;
  }

  console.log(result);

})();

The output will be:

Object {
  101: Object {
     title: "title 1" 
  }
  102: Object {
     title: "title 2" 
  }
  103: Object {
     title: "title 3" 
  }
}
Must Ckr
  • 310
  • 2
  • 5