【问题标题】:Get child item in Json without knowing the itemname [duplicate]在不知道项目名称的情况下获取 Json 中的子项目 [重复]
【发布时间】:2014-05-07 22:48:58
【问题描述】:

我有这样的答案:

    {
      "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"
        }
      }
....

问题是我想取“内容”的价值。我可以这样做:

data.files.fileWhatever.content

但我不应该知道文件的名称,所以“fileWhatever”可以是任何东西。如何跳转一级获取任意文件的内容?

我正在用 javascript 做这个

谢谢

【问题讨论】:

    标签: javascript json github get


    【解决方案1】:

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

    也就是说-伪应该是-

    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)
    

    可能应该有一些技术方法来提取价值

    【讨论】:

      【解决方案2】:

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

      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>");
      

      【讨论】:

      • 谢谢。这行得通:)
      猜你喜欢
      • 1970-01-01
      • 2013-11-20
      • 2013-12-31
      • 2014-05-08
      • 1970-01-01
      • 1970-01-01
      • 2014-05-21
      • 1970-01-01
      • 2015-01-23
      相关资源
      最近更新 更多