简体   繁体   中英

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

library address

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));

When I save it, I got this in database

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

When I var_dump json_decode, I got

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

How to get correct json format

PHP

I use Laravel as framework, and this field named data

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

public function getDataAttribute($value) {
    return json_decode($value);
}

You have posted json string in result field so you will not need to json_code before saving data in database

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

it would be work fine..

This is json encode data :

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

And again encode json string

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

Then result

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM