在不知道itemname的情况下获取Json中的子项目

Get child item in Json without knowing the itemname

本文关键字:Json 子项目 获取 情况下 不知道 itemname      更新时间:2023-09-26

我有一个这样的答案:

    {
      "url": "https://api.github.com/gists/47d8d5c3e80bc1568bda",
      "forks_url": "https://api.github.com/gists/47d8d5c3e80bc1568bda/forks",
      "commits_url": "https://api.github.com/gists/47d8d5c3e80bc1568bda/commits",
      "id": "47d8d5c3e80bc1568bda",
      "git_pull_url": "https://gist.github.com/47d8d5c3e80bc1568bda.git",
      "git_push_url": "https://gist.github.com/47d8d5c3e80bc1568bda.git",
      "html_url": "https://gist.github.com/47d8d5c3e80bc1568bda",
      "files": {
        "fileWhatever": {
          "filename": "fileWhatever",
          "type": "text/plain",
          "language": null,
          "raw_url": "https://gist.githubusercontent.com/test/47d8d5c3e80bc1568bda/raw/21aefad8f2f7aea0556360ff3a40a557b793e330/fileWhatever",
          "size": 19,
          "truncated": false,
          "content": "this is the content"
        }
      }
....

问题是我想取"content"的值。我可以这样做:

data.files.fileWhatever.content

但是我不应该知道文件的名称,所以'fileWhatever'可以是任何东西。我如何跳过一个级别来获得任何文件的内容?

我用javascript

谢谢

我认为一个解决方案——尽管可能不是一个优雅的解决方案——是在任意深度遍历键。

也就是- pseudo应该是-

find-value-by-key(key-name, json):
     for(key:json)
          if key==key-name
              return content of key
          else if key has children
              find-key(key-name, json.key-name)

应该有一些技术方法来提取

可能有更好的方法,但是:

var thefilename = "";
var thetype = "";
//etc...
for(var n in a.files)
{
    for(var fn in a.files[n])
    {
        if(fn=="filename")
            thefilename=a.files[n][fn];
        if(fn=="type")
            thetype=a.files[n][fn];
    }
}
document.write("<div>" + thefilename + "</div>");
document.write("<div>" + thetype + "</div>");