Parsing json from external url Html and JS only

<html>
<body>
 <div id="output">hi</div>
</body>
<script>
    var link="http://mywp.com/cilacap/api/get_posts/";
    var jcontent= JSON.parse(link);
    var output=document.getElementById('output');
    output.innerHTML=jcontent.id' ';
</script>

</html>

It only shows “hi”.
Can someone tell me how to show JSON items such as “id” and “postDate”
with looping but without PHP scripting?

Thanks

Related posts

Leave a Reply

3 comments

  1. Few syntactical errors, below is the right one.

    <html>
    <body>
     <div id="output">hi</div>
    </body>
    <script>
        var link='{"url":"http://mywp.com/cilacap/api/get_posts/", "id":"url_id_01"}';
        var jcontent= JSON.parse(link);
        var output=document.getElementById('output');
        output.innerHTML=jcontent.id + ' ';
    </script>
    
    </html>

    JSON Data(var link), was not parsable.

    JSON Data(var link), didnt contained any attribute called id.

    String concatenation in last line(output.innerHTML), was wrong.

  2. Try removing the quotes from:

    output.innerHTML=jcontent.id' ';
    

    and change it to:

    output.innerHTML += jcontent.id;
    

    Providing that the link is valid it should work now.

    You can also write:

    console.log(jcontent);
    

    and check if the console displays the value, or any errors that have occurred.

  3. That url is a string, not json.

    Use Ajax to get the data ( using jquery)

    var link;
    $.ajax({
    
      url: "test.html",
    
    }).done(function(data) {
    
      link = data;
    
    });
    

    Then, extract the data;

     output.innerHTML=jcontent.id;
    

    Is for the value. You get the key like this:

    ES7

    Object.entries(jcontent)
    .forEach(keyValuePair => 
    { 
        // Push to HTML
    
        var t = document.createTextNode(keyValuePair[0] + ' : ' + keyValuePair[1]);     // Create a text node
        output.appendChild(t);   
    });
    

    ES6

      Object.keys(jcontent)
      .map(key => [key, jcontent[key]])
      .forEach(keyValuePair => 
      { 
          // Push to HTML
    
          var t = document.createTextNode(keyValuePair[0] + ' : ' + keyValuePair[1]);     // Create a text node
        output.appendChild(t);   
    });
    

    ES5 (Most likely your case)

    Use function instead of arrow functions for es5:

    Object.keys(jcontent)
    .map(function(key){ [key, jcontent[key]] })
    .forEach(function(keyValuePair)
    { 
        // Push to HTML
    
        var t = document.createTextNode(keyValuePair[0] + ' : ' + keyValuePair[1]);     // Create a text node
        output.appendChild(t);   
    });
    

    Access the value:

    keyValuePair[0] // key
    keyValuePair[1] // value
    

    Ps

    If you want to use the es7 or es6 method, have a look at babeljs