skip to Main Content

I have a jquery variable like this :

var d1 = [{text:'t1',value:'1'},{text:'t2',value:'2'},{text:'t3',value:'3'},{text:'t4',value:'4'}];
console.log(d1);

When i display it in console.log, i have something similar to the image below

enter image description here

Now if i had an input in html like this :

<input id="txtstr" name="txtstr" value="[{text:'t1',value:'1'},{text:'t2',value:'2'}, {text:'t3',value:'3'},{text:'t4',value:'4'}]" type="text" />

in console.log i have :

console.log($("#txtstr").val());

enter image description here

I want to have json array in console.log when i use input (Like the first picture). I have also used json.parse but it didn’t work.

3

Answers


  1. It is because the attribute value isn’t having a value quoted, you don’t put text and value in quotes. to fix this do the following

    <input id="txtstr" name="txtstr" value='[{"text":"t1","value":"1"},{"text":"t2","value":"2"},{"text":"t3","value":"3"},{"text":"t4","value":"4"}]' type="text" />
    <script>
        var inputString = $("#txtstr").val();
        var jsonArray = JSON.parse(inputString);
        console.log(jsonArray);
    </script>

    So in pure JavaScript

      <input id="txtstr" name="txtstr" value='[{"text":"t1","value":"1"},{"text":"t2","value":"2"},{"text":"t3","value":"3"},{"text":"t4","value":"4"}]' type="text" />
      
      <script>
          var inputString = document.getElementById("txtstr").value;
          var jsonArray = JSON.parse(inputString);
          console.log(jsonArray);
      </script>
    Login or Signup to reply.
  2. It is because your input value does not follow the standard JSON format, where keys and string values are enclosed in double quotes.
    It shoutld be

    <input id="txtstr" name="txtstr" value='[{"text":"t1","value":"1"},{"text":"t2","value":"2"},{"text":"t3","value":"3"},{"text":"t4","value":"4"}]' type="text" />
    

    and your code will work fine

    Login or Signup to reply.
  3. var string = $.trim($('#txtstr').val());
    
    //adding double quotes to keys and values
    string = string.replace(/([{,])(s*)([a-zA-Z0-9_]+?)s*:/g, '$1"$3":');
    string = string.replace(/:s*'([^']+?)'/g, ':"$1"');
    
    //string to a JSON object
    var obj = JSON.parse(string);
    
    console.log(obj);
    console.log(typeof(obj));
    console.log(obj[1].value);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <input id="txtstr" name="txtstr" value="[{text:'t1',value:'1'},{text:'t2',value:'2'}, {text:'t3',value:'3'},{text:'t4',value:'4'}]" type="text" />
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search