Separate json to use it in javascript

2

I have this output of json what I want to know is how to separate each object - ie: (3,2,5 etc.) in variables to use those variables in a javascript .

Example:

{
    "procede": "1",
    "status": "1",
    "statusText": "Correct",
    "Lugares": [{
        "México": "3",
        "Ecuador": "2",
        "Tijuana": "5"
    }]
}

this is my ws the include is for a class which has a function get_places and it works since this web service has tested it and if it throws the data

 include('lugares_m.php');
 $lugares_m = new lugares_m();
$lista = $lugares_m->get_lugares();

$i=0;
foreach($lista as $key => $renglon){
    $arr2["$i"]=array("Mexico"=>$renglon->getMexico(),
        "Ecuador"=>$renglon->getEcuador(),
        "Tijuana"=>$renglon->getTijuana());
$i++;
}
$salida["procede"]="1";
$salida["status"]="1";
$salida["statusText"]="Correct";
$salida["Lugares"]=$arr2;
echo json_encode($salida,JSON_UNESCAPED_UNICODE);
return;

and this is the javascript I use

 <script>


$.ajax({
        url: 'ws_lugares.php',
        type: 'POST',
        dataType: 'json',
        data: $(this).serialize(),

    })
    .done(function (lugares) {
        console.log(lugares);
        if (!lugares.error) {
          let m = lugares["Mexico"];
          let e = lugares["Ecuador"];
          let t = lugares["Tijuana"];

          console.log(m+""+e+""+t)

        } else {
            $('.error').slideDown('slow');
            setTimeout(function () {
                $('.error').slideUp('slow');
            }, 3500);

        }
    })
    .fail(function (resp) {
        console.log(resp.responseText);
    })
    .always(function () {
        console.log("complete");
    });

        </script>
    
asked by JV93 17.10.2018 в 23:51
source

2 answers

2

What I did was store the json in a constate called json , then you should get the value of the Places like this:

const lugares = json.Lugares[0];

Here you have the values that you want but I imagine that that can vary, so to do it dynamically we obtain the indices of this object like this:

const keys = Object.keys(lugares);

and finally we go through those indexes in a forEach to go through the Places contained in the constant places like this:

keys.forEach(function(lugar){
  console.log(lugar+" tiene el valor de "+lugares[lugar]);
});

Place a console.log() so that you can see how the values are obtained there, you can set them to variables or as you wish:

const json = {
              "procede": "1",
              "status": "1",
              "statusText": "Correct",
               "Lugares": [
                      {
                      "México": "3",
                      "Ecuador": "2",
                      "Tijuana": "5"
                        }
                ]
              };
              
const lugares = json.Lugares[0];
const keys = Object.keys(lugares);

keys.forEach(function(lugar){
  
  console.log(lugar+" tiene el valor de "+lugares[lugar]);
});

Edited:

If they are always those same regions you can directly access them like this:

const json = {
              "procede": "1",
              "status": "1",
              "statusText": "Correct",
               "Lugares": [
                      {
                      "México": "3",
                      "Ecuador": "2",
                      "Tijuana": "5"
                        }
                ]
              };
              
const regiones = json["Lugares"][0];
let mexico = regiones["México"];
let ecuador = regiones["Ecuador"];
let tijuana = regiones["Tijuana"];

console.log(mexico+" "+ecuador+" "+tijuana);
    
answered by 18.10.2018 / 00:05
source
4

It is not yet compatible in some browsers but it is apt and interesting to know that it exists:

Assignment for de-structuring

  

The destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that is equivalent to the construction of arrays and literal objects.

let json = [
  {
    "procede": "1",
    "status": "1",
    "statusText": "Correct",
    "Lugares": [
      {
        "México": "3",
        "Ecuador": "2",
        "Tijuana": "5"
      }
    ]
  }
]

let [{ "Lugares":[{ México, Ecuador, Tijuana }] }] = json;

console.log( México );
console.log( Ecuador );
console.log( Tijuana );

Can you use non-ASCII characters (eg M é xico) in JS variables? ... Here the answer:)

    
answered by 18.10.2018 в 00:49