Convertir una cadena en objeto JSON


¿Cómo haces que JS piense que una cadena es JSON ?

Tengo una función que solo funciona si se le pasa un objeto JSON. Si le paso una cadena, con el mismo formato que JSON, no funciona. Así que quiero hacer que la función piense que la cadena que se le pasa es un JSON. La cadena está en el formato JSON.

También probé lo siguiente. Ingresé la cadena a través de Ajax, con el parámetro" handle as "como " JSON", y luego cuando pasé el resultado a la función, obrar.

Así que deduje que el problema no es con la cadena. ¿Cómo convierto esta cadena a JSON? Si obtengo la misma cadena a través de la solicitud ajax y luego pasarla a la función funciona, mientras que pasarla directamente no funciona.

La cadena es la siguiente:

  {
     "data": [
   {
  "id": "id1",
      "fields": [
        {
          "id": "name1",
          "label": "joker",
          "unit": "year"
        },
         {"id": "name2", "label": "Quantity"},
    ],
      "rows": [    data here....

and closing braces..
Author: ROMANIA_engineer, 2012-06-11

8 answers

var obj = JSON.parse(string);

Donde string es tu cadena json.

 318
Author: Kshitij,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-08 16:35:00

Puedes usar el JSON.parse() para eso.

Ver documentos en MDN

Ejemplo:

var myObj = JSON.parse('{"p": 5}');
console.log(myObj);
 25
Author: Sarfraz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-11 08:50:22

Tuve el mismo problema con una cadena similar como la tuya

{id:1,field1:"someField"},{id:2,field1:"someOtherField"}

El problema es la estructura de la cadena que el analizador json no estaba reconociendo que necesita crear 2 objetos en este caso. así que lo que hice es un poco tonto, solo re estructuré mi cadena y agregué el [] con esto el analizador reconoció

var myString = {id:1,field1:"someField"},{id:2,field1:"someOtherField"}
myString = '[' + myString +']'
var json = $.parseJSON(myString)

Espero que ayude,

Si alguien tiene un enfoque más elegante, por favor comparta.

 7
Author: Abraham,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-28 13:10:03
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );

Enlace: -

Http://api.jquery.com/jQuery.parseJSON /

 6
Author: sandeep patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-11 08:52:27
var Data=[{"id": "name2", "label": "Quantity"}]

Pasa la variable string al análisis Json:

Objdata= Json.parse(Data);
 2
Author: Ankita_systematix,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-03 06:25:00

JSON.parse() la función servirá.

O

Usando Jquery,

var obj = jQuery.parseJSON( '{ "name": "Vinod" }' );
alert( obj.name === "Vinod" );
 0
Author: Vinod Selvin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-03 08:23:47

Simplemente use la función eval.

var myJson = eval(theJsibStr);
 0
Author: Siyavash Hamdi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-15 06:44:43

Consideremos que tienes una cadena como

Ejemplo: "nombre: lucy, edad: 21, género: mujer"

function getJsonData(query){
    let arrayOfKeyValues = query.split(',');
    let modifiedArray =  new Array();
    console.log(arrayOfKeyValues);
    for(let i=0;i< arrayOfKeyValues.length;i++){
        let arrayValues = arrayOfKeyValues[i].split(':');
        let arrayString ='"'+arrayValues[0]+'"'+':'+'"'+arrayValues[1]+'"';
        modifiedArray.push(arrayString);
    }
    let jsonDataString = '{'+modifiedArray.toString()+'}';
    let jsonData = JSON.parse(jsonDataString);
    console.log(jsonData);
    console.log(typeof jsonData);
    return jsonData;
}

let query = "name:lucy,age:21,gender:female";
let response = getJsonData(query);
console.log(response);

`

 0
Author: shishir bondre,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-29 12:20:48