簡體   English   中英

如何使用名稱為 foo.txt 的 json 對象。 我想打印這個對象的元素?

[英]how to use a json object in which its name is foo.txt. I want to print element of this object?

我只是用 javascript 和 json 做的。 我想從 api 獲取數據,其中對象有一些細節,在這里我想打印一個名為“foo.txt”的對象的細節,有一些元素,如大小、raw_url、內容等。我想要 raw_url。

我怎樣才能完成以下工作:

document.getElementById("demo").innerHTML = data.files.foo(?)['raw_url']
Json is here :-
object {url: "https://api.github.com/gists/884c8343dca5b322bf6f", forks_url: "https://api.github.com/gists/884c8343dca5b322bf6f/forks", commits_url: "https://api.github.com/gists/884c8343dca5b322bf6f/commits", id: "884c8343dca5b322bf6f", git_pull_url: "https://gist.github.com/884c8343dca5b322bf6f.git"…}
comments: 0
comments_url: "https://api.github.com/gists/884c8343dca5b322bf6f/comments"
commits_url: "https://api.github.com/gists/884c8343dca5b322bf6f/commits"
created_at: "2015-11-19T09:35:23Z"
description: "test"
files: Object
foo.txt: Object
content: "sdfasfd"
filename: "foo.txt"
language: "Text"
raw_url: "https://gist.githubusercontent.com/anonymous/884c8343dca5b322bf6f/raw/5234994707b7b85bec9c80e50cb0b7dfca050e3b/foo.txt"
size: 7
truncated: false
type: "text/plain"

您只想訪問該屬性? 您不必使用點語法 ( myObject.foo.txt ) 訪問屬性,這顯然會導致問題。 只需使用方括號訪問它:

myObject['foo.txt']

 var myObject = { 'foo.txt': 'Hello World!' }; var div = document.createElement('div'); div.innerHTML = myObject['foo.txt']; document.body.appendChild(div);

Firefox 有Object.toSource()將對象打印為 JSON 或者您可以安裝 Firebug 並使用console.log(object)打印

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM