How does a Json object return?

-2

I just modified an HTML example with Json but it is of an array type and apparently what I want to use is an object, I believe this is the problem. json contains this information:

{"riotschmick": {"id": 585897, "name": "RiotSchmick", "profileIconId": 956, "summonerLevel": 30, "revisionDate": 1449128440000}}

I think there is something in the code to work Here is the example:

<!DOCTYPE html>
<html>
<body>


<h1>Meu Projeto</h1>
<div id="id01"></div>
<div id="id02"></div>
<script>
var xmlhttp = new XMLHttpRequest();

var url = "https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/RiotSchmick?api_key=a15c56d1-fdd7-4da2-ad9c-0f1a6585ac1b";

xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        myFunction(xmlhttp.responseText);
    }
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

function myFunction(response) {
    var arr = JSON.parse(response);
    var out = "<h1>";
    out += arr.id + arr.name + arr.summonerLevel;
    out += "</h1>";
    document.getElementById("id01").innerHTML = out;
}

</script>

</body>
</html>
    
asked by anonymous 02.12.2015 / 18:13

2 answers

2

I've already figured out the problem. This Json is a complex object, to work I did it this way:

    out += arr.riotschmick.id + arr.riotschmick.name + arr.riotschmick.summonerLevel;
    
03.12.2015 / 11:31
2

The second "JSON" you are using is not a list, so you do not need the index to access the properties of the object.

out += arr.id + arr.name + arr.summonerLevel;

Read in this JavaScript guide that explains what is and how to work with .

  

Edited: AP changed the question, JSON changed.

What is an object?

object is an independent entity with properties and type.

How do I access the properties of my object?

ObjectName.PropertyName

How do I know which property my object has?

If you do not know what properties your JavaScript object has, an option is to print it in the browser console ( console.log('') ), so you can see all the properties of your object and identify whether it is just an object or a collection of objects.

What is a collection of objects?

It is an Array of objects, that is, multiple objects grouped into a single location.

  

In the link that I mentioned in the beginning of the reply has a well explained   detailed and clear information on what an object is, I suggest you read and try   understand, if you have any questions, look in the community and   find a reply you can post a new question whenever you judge   necessary.

var obj = {
  "riotschmick": {
    "id": 585897,
    "name": "RiotSchmick",
    "profileIconId": 956,
    "summonerLe‌​vel": 30,
    "revisionDate": 1449128440000
  }
};

console.log(obj);
console.log(obj.riotschmick);
console.log(obj.riotschmick.id);
console.log(obj.riotschmick.name);
    
02.12.2015 / 18:16