Question:
I want to extract the data from this json
using Javascript
and HTML
what I need is to show the data "ID" y "NAME"
https://pastebin.com/raw/45M08KT7
{
"mohademago": {
"id": 4294825,
"name": "mohademago",
"profileIconId": 1594,
"revisionDate": 1491930966000,
"summonerLevel": 30
}
}
Answer:
The following example shows you how to do it:
1.- Access the values of a JSON Object if you know its structure.
2.- Access the values of a JSON Object if its structure is NOT known.
3.- Obtain the data from a GET request (via XMLHttpRequest)
(This only works if the request is made to the same server)
obj = { "mohademago": { "id": 4294825, "name": "mohademago", "profileIconId": 1594, "revisionDate": 1491930966000, "summonerLevel": 30 } }; html.innerHTML+="\ 1.- Acceder a los valores de un objeto JSON si conoces su estructura" html.innerHTML+="<p>id="+obj.mohademago.id; html.innerHTML+="<p>name="+obj.mohademago.name; html.innerHTML+="\ 2.- Acceder a los valores de un objeto JSON si NO conoces su estructura" display(obj,""); function display(obj,sp) { for (n in obj) { if (typeof obj[n] == 'object') { display(obj[n],n+"."); }else{ html.innerHTML+="<p>"+sp+n+"="+obj[n]; } } } html.innerHTML+="\ 3.- Obtener los datos desde una petición GET (via XMLHttpRequest)\ (Esto solo funciona si la solicitud se hace al mismo servidor)" var req = new XMLHttpRequest(); req.open('GET', 'https://pastebin.com/raw/45M08KT7', true); req.onreadystatechange = function () { if (req.readyState == 4) if (req.status == 200) { obj = JSON.parse(req.responseText); display(obj,""); } else { html.innerHTML+="<p>error "+req.status; } }; req.send(null);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="html"></div>