JD *_*cks 6 javascript jquery parsing json
我正在解析一个像这样的json字符串:
ring = JSON.parse(response);
Run Code Online (Sandbox Code Playgroud)
现在,ring
是一个对象,但是ring.stones只是一个字符串,它应该也是一个对象.
如果我打电话:
ring.stones = JSON.parse(ring.stones);
Run Code Online (Sandbox Code Playgroud)
它现在是正确的对象.
我不知道这是否是正确的行为,或者我是否有某个问题阻止其递归解析?如果它应该递归解析,是否有任何已知的问题会阻止它?
以下是解析之前的完整响应:
{"ring_id":"9","stone_count":"4","style_number":"style 4","syn10":"436.15","gen10":"489.39","syn14":"627.60", "gen14": "680.85", "可用": "是", "类型": "环", "engravings_count": "0", "engravings_char_count": "0", "engravings_band": "10","石":"[{\ "stone_id \":\ "27 \",\ "ring_id \":\ "9 \",\ "stone_shape \":\ "圆\"\"stone_x \":\"132.80 \",\ "stone_y \":\ "114.50 \",\ "stone_width \":\ "71.60 \",\ "stone_height \":\ "71.60 \",\ "stone_rotation \":\ "0.00 \" ,\"stone_number\":\" 1\"\ "stone_mm_width \":\ "5.00 \",\ "stone_mm_height \":\ "5.00 \"},{\ "stone_id \":\ "28 \",\" ring_id\":\" 9\"\ "stone_shape \":\ "圆\"\"stone_x \":\ "100.50 \",\ "stone_y \":\ "166.20 \",\" stone_width\":\" 36.20 \",\ "stone_height \":\ "36.60 \",\ "stone_rotation \":\ "0.00 \",\ "stone_number \":\ "2 \"\"stone_mm_width \":\"2.50 \",\ "stone_mm_height \":\ "2.50 \"},{\ "stone_id \":\ "29 \",\ "ring_id \":\ "9 \",\ "stone_shape \":\"轮\",\ "stone_x \":\ "200.20 \",\ "stone_y \":\ "105.10 \",\"stone_width\":\" 33.90\"\ "stone_height \":\ "33.90 \",\ "stone_rotation \":\ "0.00 \",\ "stone_number \":\ "3 \" \" stone_mm_width\":\" 2.50\"\ "stone_mm_height \":\ "2.50 \"},{\ "stone_id \":\ "30 \",\ "ring_id \":\ "9 \",\" stone_shape\":\" 轮\",\ "stone_x \":\ "165.80 \",\ "stone_y \":\ "82.50 \",\ "stone_width \":\ "35.50 \",\ "stone_height \":\"33.90 \",\ "stone_rotation \":\ "0.00 \",\ "stone_number \":\ "4 \"\"stone_mm_width \":\ "2.50 \",\ "stone_mm_height \":\" 2.50 \"}]","images":"[{\"title \":\"white gold \",\"source \":\"Style4_4_W_M.png \"},{\"title \":\"yellow gold \",\"source \":\"Style4_4_Y_M.png \"}]"}
基于mikerobi的回答,我能够弄清楚发生了什么:
这是我编码的地方:
$row = $sth->fetch(PDO::FETCH_ASSOC);
$row['stones'] = getStones($ring_id);
$row['images'] = getRingVariations($ring_id);
return json_encode($row);
Run Code Online (Sandbox Code Playgroud)
但功能getStones
和getRingVariations
返回json_encode
'字符串.我需要更改它们以返回纯字符串.
您的JSON结构是错误的,它将石头包裹在引号中,将其转换为字符串.
你的JSON看起来像:
{
stones: "[{\"stone_id":\"27\"},{\"stone_id\":\"27\"}]"
}
Run Code Online (Sandbox Code Playgroud)
它应该看起来像:
{
stones: [{"stone_id": 27},{"stone_id": 27}]
}
Run Code Online (Sandbox Code Playgroud)
编辑
看来你正在将所有值转换为字符串,包括数字,我更新了我的例子以反映这一点.
另外,我猜输出你正在编写自己的代码来序列化JSON,我强烈建议使用现有的库.