Convert Json to Array with Jquery

Asked

Viewed 1,354 times

0

I’m making an ajax request with jquery and Php like this:

// arquivo php
    $json = array(
      "status"=>"true",
      "message"=>"inserido com sucesso"
    );

    echo json_encode($json);

.

// arquivo js
    $.ajax({
        url, url,
        type: "post",
        data: dados,
        success: function(json){
          console.log(json);
        },
        error: function(){
          msg.text("Erro ao fazer requisição");
        }
      });

My console.log return {"status":"true","message":"inserido com sucesso"} and wanted to be transformed into a Java Script array, as I could do this conversion ?

  • 2

    Just add the attribute dataType: "json" to your AJAX request.

  • worked thanks, you think I’d better close the question ?

1 answer

1


Use the $.map, so transform json into array.

// arquivo js
$.ajax({
    url: url,
    type: "post",
    data: dados,
    dataType: 'json',
    success: function(json){
      let arr = $.map(json, function(el) { return el; })
      console.log(arr['status']);
      console.log(arr['message']);
    },
    error: function(){
      msg.text("Erro ao fazer requisição");
    }
});

If you only want to make PHP json an object/json in javascript, just add dataType: 'json'

// arquivo js
$.ajax({
    url: url,
    type: "post",
    data: dados,
    dataType: 'json',
    success: function(json){
      console.log(json.status);
      console.log(json.message);
    },
    error: function(){
      msg.text("Erro ao fazer requisição");
    }
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.