T
T
Tynay Bakasov2019-12-18 02:52:54
JSON
Tynay Bakasov, 2019-12-18 02:52:54

How to display the required fields from JSON?

Good day.
There is Json data on the .txt file. For example, I want to display only artist AND title , I don't need status . you need to display on the page in a div and update let's say every 5 seconds through setInterval
{"artist":"Eminem","title":"Rap God","status":"1"}

<div id="artist"></div>
<div id="title"></div>

js code (helped yesterday)
var json = 'https://www.site.com/json.txt'
function init(){
 let _json = JSON.parse(json)
//где-то тут надо сделать выбор, но что только не пробовал, не получается.
 let artist = document.getElementById('artist');
 let title= document.getElementById('title');
  artist.innerHTML = _json.artist;
  title.innerHTML = _json.title;
 setInterval(init,1000)
}
setInterval(init,1000)

I would be very grateful, thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya Savinykh, 2019-12-18
@Yobanaris

Try like this!

var url_json = 'https://www.site.com/json.txt';
function init(){
    fetch(url_json)
        .then(response => response.json())
        .then(_json => {
            let artist = document.getElementById('artist');
            let title= document.getElementById('title');
             artist.innerHTML = _json.artist;
             title.innerHTML = _json.title;
        });
}
setInterval(init,1000);

var url_json = 'https://www.site.com/json.txt';
function init(){
    fetch(url_json)
        .then(response => response.json().then(_json => {
            let artist = document.getElementById('artist');
            let title= document.getElementById('title');
             artist.innerHTML = _json.artist;
             title.innerHTML = _json.title;
        }));
}
setInterval(init,1000);

There is an error in your example - The JSON.parse() method parses a JSON string, and you are passing not a JSON string, but a url

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question