[英]json.parse unexpected token error
I'm trying to parse string to json object but i always get the same error SyntaxError: unexpected token ' 我正在尝试将字符串解析为json对象,但我总是遇到相同的错误SyntaxError:意外令牌'
var data = ('{' + fields.productName.toString() + ":" + parseInt(fields.quantity.toString()) + '}' );
I tried few variation of this but nothing works. 我尝试了很少的变化,但没有任何效果。
You need to have quotes around the value name 您需要在值名称周围加上引号
data = ('{\"' + fields.productName.toString() + "\":" + parseInt(fields.quantity.toString()) + '}' );
But you should not generate json manually, because now you would need to escape all quotes that fields.productName.toString() includes. 但是您不应该手动生成json,因为现在您需要转义fields.productName.toString()包含的所有引号。 You should use JSON.stringify instead.
您应该改用JSON.stringify 。
Best way to avoid issues : 避免问题的最佳方法:
var data = {};
data[fields.productName.toString()] = parseInt(fields.quantity.toString());
PS Leverage the beauty of JS objects, Do not re-invent the wheel by constructing object using strings :) PS利用JS对象的美丽,不要通过使用字符串构造对象来重新发明轮子:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.