Jquery : Automatic type conversion during parse JSON

后端 未结 4 764
猫巷女王i
猫巷女王i 2021-01-14 22:58


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 n

4条回答
  •  再見小時候
    2021-01-14 23:43

    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.

提交回复
热议问题