L
L
Lavrenty Fedotov2017-04-07 23:39:52
JavaScript
Lavrenty Fedotov, 2017-04-07 23:39:52

How to parse and output JSON to HTML using JavaScript?

Greetings.
It is necessary to parse JSON, which is located on another site, and then read this json and display it as a table in html on the site.
I think that it is possible to do this using javascript using the JSON.parse method , but I have never worked with JavaScript and have not found an example of parsing exactly the site url.
And I do not fully understand how to output using innerHTML \ outerHTML
Please help. What is the easiest way to implement this and if there are examples, it would be ideal.
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Di Ma, 2017-04-08
@dimentimor

For example:

var data = {
  name: 'Jack',
  items: {
    dog: 1,
    car: 1,
    phone: 2,
  },
};

// объект в json
var json = JSON.stringify(data); // {"name":"Jack","items":{"dog":1,"car":1,"phone":2}}

// json в объект
var obj = JSON.parse(json); // объект

When we get json, we convert it into an object, and then, depending on the data structure
var data = JSON.parse('{"name":"Jack","items":{"dog":1,"car":1,"phone":2}}');

var header = '<h2>My name is ' + data.name + '</h2>';
var list = '';

for (var i in data.items) {
  list += '<li>' + i + ': ' + data.items[i] + ' шт. </li>';
}

document.getElementById('div').innerHTML += header;
document.getElementById('div').innerHTML += '<ul>' + list + '</ul>';

// Конечно, лучше создавать элементы через
// var div = document.createElement('div');
// наполнять через div.innerHTML = "text";
// и добавлять их через element.appendChild(div);

1978d2a5f51544268810b11dc1357ee7.jpg

@
@ksider, 2017-04-08
_

something like this in jquery

$.getJSON(url_json, function(data){
 $.each(data.items, function(key, val) {

// перебор масива

  });
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question