2017-04-04 18 views
0

JavaScriptを使用してJSONファイルのネストされたコンテンツを読み込もうとしています。ここでJavaScriptを使用してネストされたJSONを読み取る

は私のJavaScriptのである:

{ 
    "id": "life-events", 
    "type": "category", 
    "title": "Life events", 
    "description": "When big things happen - having a baby, losing your job, getting divorced or retiring\n - it helps to be in control of your money\n", 
    "contents": [ 
     { 
      "id": "setting-up-home", 
      "type": "category", 
      "title": "Setting up home", 
      "description": "Deciding whether to rent or buy, working out what you can afford and managing\n money when sharing with others\n", 
      "contents": [ 
      ] 
     }, 
     { 
      "id": "young-people-and-money", 
      "type": "category", 
      "title": "Leaving school or college", 
      "description": "", 
      "contents": [ 
      ] 
     }, 
     { 
      "id": "having-a-baby", 
      "type": "category", 
      "title": "Having a baby", 
      "description": "", 
      "contents": [ 
      ] 
     } 
    ] 
}, 

ネストされたJSONは '未定義' として表示されます。

<script> 
var obj, xmlhttp, myObj, x, txt = ""; 
var request = new XMLHttpRequest(); 
request.open('GET', 'https://private-c01be-moneyadviceservice.apiary-mock.com/locale/categories.json'); 
request.setRequestHeader("Content-type", "application/json"); 
request.onreadystatechange = function() { 
if (this.readyState === 4) { 
console.log('Status:', this.status); 
console.log('Headers:', this.getAllResponseHeaders()); 
console.log('Body:', this.responseText); 

    myObj = JSON.parse(this.responseText); 

    for (x in myObj) { 
     txt += "<h2>" + myObj[x].title + "</h2><p>" + myObj[x].description + "</p><br/>"; 
     txt += "<h3>" + myObj[x].contents.title + "</h3><p>" + myObj[x].contents.description + "</p><br/>"; 
    } 

    document.getElementById("MAS").innerHTML = txt; 
    } 
}; 

request.send(); 
</script> 

そしてここでは、JSONファイルです。ネストされたデータにアクセスするにはどうすればよいですか?

彼らは以下のように配列されているので、あなたが同様にcontentsをループする必要があり、私はこのトピックについて無数の記事を読みましたが、どれも本当にこのインスタンスで

+1

内容はオブジェクトの配列です。それをループしてmyObj [x] .contents [y] .titleなどを取得する必要があります。 – Christopher

+1

@Christopher私も気づいた。これを回答として投稿する必要があります。 –

+0

@ LuisEstevezあなたが望むなら、先に進むことができます。私は私の電話の上にあるので、少し面倒です。 :) – Christopher

答えて

2

を助けなかった:ここ

for (x in myObj) { 
    txt += "<h2>" + myObj[x].title + "</h2><p>" + myObj[x].description + "</p><br/>"; 
    for(y in myObj[x].contents){ 
    txt += "<h3>" + myObj[x].contents[y].title + "</h3><p>" + myObj[x].contents[y].description + "</p><br/>"; 
    } 
    } 

されますJSBin

+0

私はOPが3行目を外側のループに残したいと思っています。ちょうどちょうど ' – Christopher

+0

@Christopherはい、あなたは正しいです:) – Lotus91

+0

Thanks Lotus91、that worked –

1

contentsは配列なので、myObj[x].contents.titleにアクセスすることはできません。それはプロパティのためにmyObj[x].contentsを反復する必要があります。

関連する問題