I
I
Islam Ibakaev2019-05-07 23:03:03
JSON
Islam Ibakaev, 2019-05-07 23:03:03

Why php json_encode() and js JSON.parse() are not friends and how to reconcile them?

I'm working on a laravel + vue project, I'm trying to throw data from the database into vue through a template, like this

@extends('layouts.app')
@section('content')
    <group-task :task="'{{ json_encode( $task ) }}'"></group-task>
@endsection

In a component, I'm trying to pass data down to the children through the homeTask property (the relevant piece of the component)
<template>
<div>
    <TrainerTaskNew :homeTask="JSON.parse(task)" v-if="task.trainer='Ментальный счёт'"></TrainerTaskNew>
    <RombTrainerNew :homeTask="JSON.parse(task)" v-else></RombTrainerNew>
</div>
</template>

Basically json_encode() gave me this string
'{"id":6,"trainer":"Флеш-карты","level":"-1 = -10+9","req_formulas":"["-2 = -5+3","-4 = -5+1"]","minmax":"от 1 до 9","quantity":20,"nums":4,"subtraction":1,"group_id":1,"created_at":"2019-05-07 19:43:35","updated_at":"2019-05-07 19:43:35"}'

JSON.parse() cannot parse this string, throws an error. Suggest a solution to the problem.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Immortal_pony, 2019-05-08
@devellopah

This is not how you can do it, because when inserted into html, the encoded quotes are converted back.
Here's a safe coding:
And on the client, respectively:
JSON.parse(decodeURIComponent(serialized))

R
Roman Kitaev, 2019-05-07
@deliro

5cd1e65b8be7d521540115.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question