将JSON对象的键转换为点表示法路径

时间:2012-11-28 04:08:11

标签: javascript json

我没有使用已知的点符号访问深层对象,而是想做相反的事情:从深层对象的键构建点符号字符串。

所以给出以下JSON对象:

{
  great:{
    grand:{
      parent:{
        child:1
      },
      parent2:1
    }
  }
}

我想获得以下数组路径:

[
  "great.grand.parent.child",
  "great.grand.parent2"
]

提前致谢!

2 个答案:

答案 0 :(得分:6)

试试这个。但我不知道你为什么需要这个。

function path(a) {
  var list = [];
  (function(o, r) {
    r = r || '';
    if (typeof o != 'object') {
      return true;
    }
    for (var c in o) {
      if (arguments.callee(o[c], r + "." + c)) {
        list.push(r.substring(1) + "." + c);
      }
    }
    return false;
  })(a);
  return list;
}
var a = {
  great:{
    grand:{
      parent:{
        child:1
      },
      parent2:1
    }
  }
};
console.log(JSON.stringify(path(a)));

答案 1 :(得分:1)

var path = function (a) {
  var list = [];
  (function(o, r) {
    r = r || '';
    if (_.isArray(o)) {
      return true;
    }
    for (var c in o) {
      if (arguments.callee(o[c], r + (r!=""?"[":"") + c + (r!=""?"]":""))) {
        list.push(r + (r!=""?"[":"") + c + (r!=""?"]":""));
      }
    }
    return false;
  })(a);
  return list;
};

输入类似这样的东西(输入错误的深JSON对象):

{
    "email": [
      "Enter a valid email."
    ],
    "billing": {
      "name": [
        "Enter a billing name."
      ],
      "line1": [
        "Enter a street address or PO box."
      ],
      "city": [
        "Enter a city."
      ],
      "state": [
        "Enter your state abbreviation."
      ],
      "zip": [
        "Enter a valid 5-digit zip."
      ]
    },
    "shipping": {
      "name": [
        "Enter a billing name."
      ],
      "line1": [
        "Enter a street address or PO box."
      ],
      "city": [
        "Enter a city."
      ],
      "state": [
        "Enter your state abbreviation."
      ],
      "zip": [
        "Enter a valid 5-digit zip."
      ]
    },
    "payment": {
      "number": [
        "Enter a valid credit card number."
      ],
      "exp_month": [
        "Enter a valid expiration month."
      ],
      "exp_year": [
        "Enter a valid expiration year."
      ],
      "cvc": [
        "Enter a valid CVC."
      ]
    }
 }

你得到这样的输出(数组表示法中的输入名称,通过客户端模板附加错误)

["email", "billing[name]", "billing[line1]", "billing[city]", "billing[state]", "billing[zip]", "shipping[name]", "shipping[line1]", "shipping[city]", "shipping[state]", "shipping[zip]", "payment[number]", "payment[exp_month]", "payment[exp_year]", "payment[cvc]"]