如何使用JSON创建输出

时间:2018-04-23 15:44:20

标签: javascript json node.js

我有一个像这样结构的json文件:

[
    {
    "style":"h1",
    "content":"this is h1"
    },
    {
      "style":"p",
      "content":"this is a long paragraphe "
    },
    {
      "style":"img",
      "content":"image1.jpg"
    },
    {
    "style":"h2",
    "content":"this is h2"
    },
    {
    "style":"h3",
    "content":"this is h3"
    },
    {
    "style":"h1",
    "content":"this is h1 number 2"
    },
    {
      "style":"p",
      "content":"this is a long paragraphe 2 "
    },
    {
      "style":"img",
      "content":"image2.jpg"
    },
    {
    "style":"h2",
    "content":"this is h2 number 2"
    },
    {
    "style":"h3",
    "content":"this is h3 number 2"
    }  
]

我需要它在JavaScript中输出如下:

this is h1
this is h2
this is h3
this is a long paragraphe
image1.jpg 
this is h1 number 2
this is h2 number 2
this is h3 number 2
this is a long paragraphe 2
image2.jpg

2 个答案:

答案 0 :(得分:0)

Array.prototype.forEach()完成这项工作。迭代列表也是如此。



var data=[
  {"style":"h1","content":"this is h1"},
  {"style":"p","content":"this is a long paragraphe "}
];
data.forEach(function(elt){
  console.log(elt.content);
});
for (var i=0; i<data.length; i++){
  console.log(data[i].content);
}
&#13;
&#13;
&#13;

如果尚未提取您的json文件,请使用ajax请求获取它并按上述步骤操作。 (ajax请求简介:https://www.w3schools.com/xml/ajax_intro.asp

&#13;
&#13;
// creates an Ajax object to fetch the content of a file
var ajax=new XMLHttpRequest();
ajax.open("GET","data.json",false);
ajax.send();

// dataString contains the .json file as a string
var dataString=ajax.response;

// we parse it (ie convert it into a javascript object)
var dataObject=JSON.parse(dataString);

// and we iterate through it
for (var i=0; i<dataObject.length; i++){
  console.log(dataObject[i].content);
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我会假设你正在使用jQuery并且你正试图获取文件而只打印没有html标签的“内容”。 我假设很多因为问题不明确。

请不要downvote!我正在努力帮助OP解决问题。

<div id="output">
    <!-- here we'll write the output-->
</div>
<script>
    $.get('your_json_file.json',function(data){
        var data = JSON.parse(data); //may not be neccesary, it depends on how you output your json
        $.each(data, function(index, value){
            //here you get each object of the array. You only want the content
            $('#output').append('<p>' + value.content + '</p>');
        });
    });
</script>