I am using laravel and I want to seed json in my database. So what I'm doing is json_encode($array). But this puts "\" on every " (double quote), which I don't want, how can I generate json from array without putting slashes in fron of every double quote?
This is the array:
$fields = [
[
'name' => 'image',
'type' => 'file',
'view' => 'image',
'validations' => 'required|image',
'label' => 'image'
]
];
When I use json_encode($fields) it stores it in the db like:
"[{\"name\":\"image\",\"type\":\"file\",\"view\":\"image\",\"validations\":\"required|image\",\"label\":\"image\"}]"
I don't want those slashes, because I have to use json_decode() twice because of them. Also that $casts attribute in Laravel decodes them only once.
FIX This is what I tried and it worked
I have this in my model:
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'fields' => 'array',
'translatable_fields' => 'array'
];
So it should decode it automatically. This is how was I saving it in the database from the seeder:
$moduleTemplate = new ModuleTemplate;
$moduleTemplate->translateOrNew('en')->name = 'Image with text';
$moduleTemplate->translateOrNew('bg')->name = 'Снимка с тескт';
$moduleTemplate->view = 'section-1';
$fields = collect([
[
'name' => 'image',
'type' => 'file',
'view' => 'image',
'validations' => 'required|image',
'label' => 'image'
]
]);
$moduleTemplate->fields = $fields->toJson();
$translatableFields = collect([
[
'name' => 'title',
'type' => 'text',
'view' => 'input',
'validations' => 'required|string|max:190',
'label' => 'title'
],
[
'name' => 'text',
'type' => 'wysiwyg',
'view' => 'wysiwyg',
'validations' => 'required|string',
'label' => 'text'
]
]);
$moduleTemplate->translatable_fields = $translatableFields->toJson();
$moduleTemplate->save();
And it was putting the slashes everytime
What I did to fix it was simply to remove ->toJson() from the arrays and it worked
Simply change your quotes format from
json_encode('"glossary": {"title": "example glossary"}');
to
json_encode("'glossary': {'title': 'example glossary'}");
Edit based on your comments
With
$fields = [ [ "name" => "image", 'type' => 'file', 'view' => 'image', 'validations' => 'required|image', 'label' => 'image' ] ];
When I do
json_encode($fields)
It returns me
[{"name":"image","type":"file","view":"image","validations":"required|image","label":"image"}]
Using Laravel 4.2, not tested with Laravel > 5
You might be doing something wrong with your JSON data
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With