Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make input string value to json object

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading