How to convert a string into an object in Javascript?

Asked

Viewed 1,787 times

1

I have this code:

<html><head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta name="robots" content="noindex, nofollow">
  <meta name="googlebot" content="noindex, nofollow">
  <script type="text/javascript" src="//code.jquery.com/jquery-1.6.2.js"></script>
  <link rel="stylesheet" type="text/css" href="/css/normalize.css">
  <link rel="stylesheet" type="text/css" href="/css/result-light.css">
  <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.14/jquery-ui.min.js"></script>
  <link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.14/themes/black-tie/jquery-ui.css">
  <title>jQueryUI 1.8.14 Autocomplete</title>
  <script type="text/javascript">


function montaAutocomplete(source) {
  
  var dados = [{ label: "Agostinho", value: "1" }];
  //DADOS: VARIÁVEL ESTÁTICA
  document.getElementById('resultado').innerHTML = dados;

  //SOURCE: VEM DO BANCO DE DADOS
  document.getElementById('resultado1').innerHTML = source;

    $("#descricao").autocomplete({
        source: dados,
        minLength: 1, //quantidade de caracteres para começar a buscar
        select: function (event, ui) {
            //evento de quando você seleciona uma opção        
            $("#descricao").val(ui.item.label);
            $("#id").val(ui.item.value);
            event.preventDefault();
        }
    });
   
}

function busca(x){

  $.ajax({
    type:"GET",
    url: "autocomplete.php?q=" + x,
    dataType:'text',
    success : function(data) {
        montaAutocomplete(data);
      }
    });

}






</script>
</head>
<body>
  <input type="text" id="descricao" onkeyup="busca(this.value);" class="ui-autocomplete-input" autocomplete="off" role="textbox" aria-autocomplete="list" aria-haspopup="true">
<input type="text" name="id" id="id">
<br>
dados:<br><div id="resultado"></div>
<br>
source:<br>
<div id="resultado1"></div>

It is an application with the autocomplete feature which communicates with the file autocomplete.php which, from the keystrokes typed by the user, it returns the following code.:

Example, if the user type in the input the name agostinho, the autocomplete will return

[{ label: "Augustine", value: "1" },];

However I’m having difficulty passing this return to the function montaAutocomplete(source) because, apparently, javascript interprets it as a common string and not as an object.

See that in the image below the variable dados , which is static, is interpreted as object, whereas the variable source is interpreted as a common string. string_para_objeti

How can I convert this result that is returned from autocomplete to a javascript object?

2 answers

1

The best solution would be jQuery.parseJSON

Documentation

var obj = jQuery.parseJSON('[{ label: "Agostinho", value: "1" }]');

example how you could use in the function montaAutocomplete:

function montaAutocomplete(source) {

  var dados = [{ label: "Agostinho", value: "1" }];
  //DADOS: VARIÁVEL ESTÁTICA
  document.getElementById('resultado').innerHTML = dados;

  // exemplo
  var obj = jQuery.parseJSON(source);
  //SOURCE: VEM DO BANCO DE DADOS
  //document.getElementById('resultado1').innerHTML = source;
  console.log(obj); // verifica se esta tudo ok


  $("#descricao").autocomplete({
    source: dados,
    minLength: 1, //quantidade de caracteres para começar a buscar
    select: function (event, ui) {
        //evento de quando você seleciona uma opção        
        $("#descricao").val(ui.item.label);
        $("#id").val(ui.item.value);
        event.preventDefault();
      }
  });

}

or even better before you call the function if possible parse the object, so you no longer have to do it within the function:

var objeto = jQuery.parseJSON(data);
montaAutocomplete(objeto);

-3

I managed to solve with a little research, rs.

If someone is in this situation, use as follows:

  var dados = eval(source);

The function Eval() evaluates or executes an argument.

If the argument is an expression, Eval() evaluates the expression. If the argument is one or more Javascript statements, Eval() executes the statements.

  • You’re getting negative because eval is dangerous and should rarely be used. In your case, the native features of JSON.parse.

Browser other questions tagged

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