当通过JSON.stringify保存数据时无法执行json_decode


Can't do json_decode when saved data by JSON.stringify

库地址

https://github.com/douglascrockford/JSON-js

.HTML

<input name="title[]" type="text" value="a1">
<input name="content[]" type="text" value="a2">
<input name="title[]" type="text" value="b1">
<input name="content[]" type="text" value="b2">
<input id="result" type="text">

JavaScript

var result = [];
$('[name="title[]"]'].each(function(index) {
    content = $('[name="content[]"]').eq(index).val();
    result.push({title: $(this).val(), content: content});
});
$('#result').val(JSON.stringify(result));

当我保存它时,我在数据库中得到了这个

"[{'"title'":'"a'",'"content'":'"a2'"},{'"title'":'"b'",'"content'":'"b2'"}]"

当我var_dump json_decode时,我得到了

string '[{"title":"a","content":"a2"},{"title":"b","content":"b2"}]' (length=59)

如何获得正确的 json 格式

.PHP

我使用Laravel作为框架,这个字段命名为data

public function setDataAttribute($value) {
    $this->attributes['data'] = json_encode($value);
}
public function getDataAttribute($value) {
    return json_decode($value);
}
您已在

result字段中发布json string,因此在将数据保存到数据库之前无需json_code

public function setDataAttribute($value) {
    $this->attributes['data'] = $value;
} 

它会很好。.

这是 json 编码数据:

 '[{"title":"a","content":"a2"},{"title":"b","content":"b2"}]'

并再次编码 json 字符串

json_encode('[{"title":"a","content":"a2"},{"title":"b","content":"b2"}]');

然后结果

"[{'"title'":'"a'",'"content'":'"a2'"},{'"title'":'"b'",'"content'":'"b2'"}]"