将JSON对象从textarea转换为javaScript对象并打印到表中(严格来说是JavaScript)

时间:2017-07-26 18:21:13

标签: javascript html json

我有一个文本区域(HTML),我将手动输入Json对象,我    想将其转换为javaScript对象并将其打印到表中。一世    尝试但无法弄清楚。 (仅限javaScript)。用于演示    目的我试图在段落中打印它。

 function addJson(){
    var textAreaValue = document.getElementById('jsonTextArea').value;
    var jsObject = JSON.parse(textAreaValue);
    document.getElementById("demo").innerHTML = jsObject.name+"  " 
    +jsObject.city;
    }
    //example json object : { "name":"John", "age":30, "city":"New York"}
<p id="demo"></p>
    <textarea   id = "jsonTextArea" placeholder = "JSON Text..."></textarea>
   
    <input type="button" id="addJson"  onclick="addJson()" value="Add">
    
   

   

3 个答案:

答案 0 :(得分:0)

&#13;
&#13;
var addJson = function() {
    var textAreaValue = document.getElementById('jsonTextArea').value;
    var jsObject = JSON.parse(textAreaValue);
    console.log( jsObject );
    document.getElementById("demo").innerHTML = jsObject.name+"  " +jsObject.city;
}
&#13;
<p id="demo"></p>
<textarea   id = "jsonTextArea" placeholder = "JSON Text..."></textarea>

<input type="button" id="addJson"  onclick="addJson()" value="Add">
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我能找到的唯一错误是函数没有被正确声明。

&#13;
&#13;
var addJson = function(){
  var textAreaValue = document.getElementById('jsonTextArea').value;
  var jsObject = JSON.parse(textAreaValue);
  document.getElementById("demo").innerHTML = jsObject.name+"  " 
  +jsObject.city;
}
&#13;
<p id="demo"></p>
<textarea   id = "jsonTextArea" placeholder = "JSON Text..."></textarea>

<input type="button" id="addJson"  onclick="addJson()" value="Add">
&#13;
&#13;
&#13;

如果你想要一个内联脚本:

<p id="demo"></p>
<textarea   id = "jsonTextArea" placeholder = "JSON Text..."></textarea>

<input type="button" id="addJson"  onclick="addJson()" value="Add">
<script>
  var addJson = function(){
    var textAreaValue = document.getElementById('jsonTextArea').value;
    var jsObject = JSON.parse(textAreaValue);
    document.getElementById("demo").innerHTML = jsObject.name+"  " 
    +jsObject.city;
  }
</script>

答案 2 :(得分:0)

一旦你的javascript正确添加了单词&#34; function&#34;之前&#34; addJson(){&#34;