【问题标题】:Stuck working with JSON object坚持使用 JSON 对象
【发布时间】:2012-05-24 20:15:29
【问题描述】:

我有一个类似于

的 JSON 对象
{
   "mydata":[
            "one",
            "two",
            "three"
            ],
   "outside":[
               {
                 "vals":["four", "five", "six"],
                 "soso":{"seven", "eight", "nine"]               
               },
               {
                 "vals":["four", "five", "six"],
                 "soso":{"seven", "eight", "nine"]               
               },
               {
                 "vals":["four", "five", "six"],
                 "soso":{"seven", "eight", "nine"]               
               },
              ]
   "inside":[]

我正在尝试使用 jquery 在“外部”上运行 $.each,这样我就可以从“外部”获取每个 vals 值集,但我没有得到任何东西,但我放弃了希望有人可以提供帮助,但我失败了,可悲地失败了

【问题讨论】:

  • 请提供更完整的代码示例
  • 您的 JSON 无效(即“soso”值以对象开头,但以数组结尾 - 此外,“inside”之前没有逗号,末尾没有右大括号)。您可以通过jsonlint.com 运行它进行测试。一旦你有一个有效的 JSON 对象,回来再次解释你的问题。
  • 扩展 robrich 所说的内容......请引用适用的 Jquery。此外,描述它如何惨遭失败可能会有所帮助。 (是否返回错误数据?是否返回空值?页面中的 javascript 是否完全关闭?)

标签: javascript jquery foreach


【解决方案1】:

outside 内,对象soso 应该是这样的

"soso":["seven", "eight", "nine"] 然后

$.each(json.outside, function() {
    this.vals.each(function(index, val) {
       console.log(val); // output: "four", "five", "six"
    });

   this.soso.each(function(index, val) {
       console.log(val); // output: "seven", "eight", "nine
    });
});

【讨论】:

    【解决方案2】:

    使用 jQuery:

    $.each(jsonObj.outside, function () {
        var i = this; // The current item
    });
    

    【讨论】:

      猜你喜欢
      • 2011-12-07
      • 2020-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多