2


Is there a way to specify type while parsing Json, so that the conversion happens automatically.

So I have the jsonData, and the x and y values needs to be number. So, the only way I can think about is looping and converting each. Any better logic, or efficient way?

var jsonData = '[{"x:"1", "y":"2"}, {"x:"3", "y":"4"}]'
var needed = [{x:1, y:2}, {x:3, y:4}]
var vals = $.parseJSON(jsonData);
//
var Coord = function(x, y){
this.x = x;
this.y = y;
}
var result = [];
function convert(vals) {
for (var i=0,l=vals.length; i<l; i++) {
        var d = vals[i];
        result.push(new Coord(Number(d.x), Number(d.y)));
    };
}   
bsr
  • 57,282
  • 86
  • 216
  • 316

4 Answers4

10

The JSON in the jsonData variable is not valid. Only the attribute should be inside of the double quotes. Whenever you convert data to JSON, use a parser (explained on json.org) and don't write it by hand. You can always check if JSON is valid by using tools like JSONLint.

Any number (integers, decimal, float) are valid JSON data types and doesn't have to be encapsulated with double quotes.

This is valid JSON: [{"x": 1, "y": 2}, {"x": 3, "y": 4}]

However, if you don't have control over the source and retrieve the JSON with ajax you can provide a callback function to the dataFilter option. If you're using jQuery 1.5 there's also converters which are generalized dataFilter callbacks.

I suspect that the x and y coords could be a decimal number which is why I chose to use parseFloat instead of parseInt in the examples below.

Example using a dataFilter callback function (pre jQuery 1.5):

$.ajax({
    url: "/foo/",
    dataFilter: function(data, type){
        if (type == "json") {
            var json = $.parseJSON(data);
            $.each(json, function(i,o){
                if (o.x) {
                    json[i].x = parseFloat(o.x);
                }
                if (o.y) {
                    json[i].y = parseFloat(o.y);
                }
            });
        }
        return data;
    },
    success: function(data){
        // data should now have x and y as float numbers
    }
});

Example using a converter (jQuery 1.5 or later):

$.ajaxSetup({
    converters: {
        "json jsoncoords": function(data) {
            if (valid(data)) {
                $.each(data, function(i,o){
                    if (o.x) {
                        data[i].x = parseFloat(o.x);
                    }
                    if (o.y) {
                        data[i].y = parseFloat(o.y);
                    }
                });
                return data;
            } else {
                throw exceptionObject;
            }
        }
    }
});

$.ajax({
    url: "/foo/",
    dataType: "jsoncoords"
}).success(function(data){
    // data should now have x and y as float numbers
});
mekwall
  • 28,614
  • 6
  • 75
  • 77
  • thank you for the detailed answer.. I would ultimately may use ajax.. thanks again – bsr Apr 29 '11 at 17:23
  • @bsreekanth, I'm glad to be of help! If you're not using ajax I hope that you will be able to incorporate some of the code above to get the desired result. Happy Walpurgis night! – mekwall Apr 29 '11 at 17:25
1

I had the same problem. In one line of code, I remove any quotes that are immediately before or after a numeral, or before a minus sign.

var chartData = $.parseJSON(rawData.replace(/"(-?\d)/g, "$1").replace(/(\d)"/g, "$1"));

In my case it was coming via AJAX from PHP code which I have control over, and I later found out I could simply use the JSON_NUMERIC_CHECK - see PHP json_encode encoding numbers as strings.

These solutions convert anything that looks like a number to a number. So if you can have something that looks like a number but needs to be treated as a string, you will need to go and figure out something else, depending on your data.

Community
  • 1
  • 1
Peter Smartt
  • 358
  • 3
  • 11
  • +1 Recommended as last resource. In my case, I used this regexp: `$.parseJSON(rawData.replace(/"(-?[\d]+\.?[\d]+)"/g,"$1")` as I had values like "80FF00" which were being treated as numbers. – lepe Feb 03 '16 at 06:54
1

The only way is to loop through you JSON data and convert the strings you find into numbers using parseInt("2");.

Luca Matteis
  • 29,161
  • 19
  • 114
  • 169
0

If you have control of the json source you can remove the quotes from the coordinates.

Acording to json.org, a value can be a sting, number, object, array, true, false, or null. A string is identified as a sequence of characters inclosed in douple quotes. A numeric value not contained in quotes should be interpeted as a number. You might to verify with the parser engine that is in use.

If your just consuming the json, the datafilter and converter methods, mention already, would be the most jquery way to solve the task.

Robert Beuligmann
  • 1,434
  • 10
  • 13
  • well, I use jQuery, and as per http://api.jquery.com/jQuery.parseJSON/ I need to have "" .. thanks – bsr Apr 29 '11 at 17:40
  • @bsreekanth, you only need double quotes for the attributes, not for the values. `[ { "x": 35.21423, "y": 14.32543 } ]` is valid JSON. You can always use [JSONLint](http://jsonlint.com/) to check :) – mekwall Apr 29 '11 at 17:52
  • It is proper json and it is parsed correctly in jquery. Quick test in firebug to prove it. >>> $.parseJSON('{"test":1.23}'); Result: Object { test=1.23} Sounds like the jquery documentation is mistaken. – Robert Beuligmann Apr 29 '11 at 19:32
  • Another side note from api.jquery.com/jQuery.parseJSON: "Where the browser provides a native implementation of JSON.parse, jQuery uses it to parse the string." So its still relevant to test the actual implementation of the parser your are using. – Robert Beuligmann Apr 29 '11 at 19:40