Convert String to Json in php

0

I can not convert a string to a json , when I try with json_decode() it returns a value null .

The string that I try to convert are like these:

  

[{id: 6, text: "10", item: 0}, {id: 7, text: "45", item: 1}, {id: 8, text: "3 ^ 2", item : 2}, {id: 9, text: "6", item: 3}, {id: 10, text: "666", item: 4}]

or this:

  

[{id: 11, text: "18", item: 0}, {id: 12, text: "16", item: 1}, {id: 13, text: "36", item: 2 }]

and that other:

  

[{id: 14, text: "12", item: 0}, {id: 15, text: "55", item: 1}, {id: 16, text: "111", item: 2 }, {id: 17, text: "9", item: 3}]

They are examples of what I am trying to convert and I try it in the following way:

json_decode($valores[$clave]["respuestas"])

    
asked by Pablo Contreras 06.07.2017 в 18:58
source

2 answers

3

The error is in the quotes of key just add them to get a value like this:

  

[{"id": 6, "text": "10", "item": 0}, {"id": 7, "text": "45", "item": 1}, {" id ": 8," text ":" 3 ^ 2 "," item ": 2}, {" id ": 9," text ":" 6 "," item ": 3}, {" id ": 10 , "text": "666", "item": 4}]

And indeed json_decode() works perfectly.

    
answered by 06.07.2017 / 20:03
source
2

Your JSON is incorrect, you are missing the quotes in the element names .

Try this JSON:

[{
    "id": 6,
    "text": "10",
    "item": 0
}, {
    "id": 7,
    "text": "45",
    "item": 1
}, {
    "id": 8,
    "text": "3^2",
    "item": 2
}, {
    "id": 9,
    "text": "6",
    "item": 3
}, {
    "id": 10,
    "text": "666",
    "item": 4
}]

The code that I used to test if you like the JSON to PHP is this, in case you want to do more tests:

<?php
$txt = '[{
    "id": 6,
    "text": "10",
    "item": 0
}, {
    "id": 7,
    "text": "45",
    "item": 1
}, {
    "id": 8,
    "text": "3^2",
    "item": 2
}, {
    "id": 9,
    "text": "6",
    "item": 3
}, {
    "id": 10,
    "text": "666",
    "item": 4
}]';


$var = json_decode($txt);

var_dump($var);

switch(json_last_error()) {
        case JSON_ERROR_NONE:
            echo ' - Sin errores';
        break;
        case JSON_ERROR_DEPTH:
            echo ' - Excedido tamaño máximo de la pila';
        break;
        case JSON_ERROR_STATE_MISMATCH:
            echo ' - Desbordamiento de buffer o los modos no coinciden';
        break;
        case JSON_ERROR_CTRL_CHAR:
            echo ' - Encontrado carácter de control no esperado';
        break;
        case JSON_ERROR_SYNTAX:
            echo ' - Error de sintaxis, JSON mal formado';
        break;
        case JSON_ERROR_UTF8:
            echo ' - Caracteres UTF-8 malformados, posiblemente están mal codificados';
        break;
        default:
            echo ' - Error desconocido';
        break;
    }
    
answered by 06.07.2017 в 19:11