如何轻松地使用javascript函数从json字符串中解析出特定对象

时间:2016-09-13 08:17:13

标签: javascript json

我想提取每个字段并将它们放入javascript中自己的变量

{
  "did": "00022B9A000000010001",
   "ps": -1,
   "hostName": "zs-dptpre-002.mr.corp.l.com",
   "ipAddress": "10.4.225.29"
}

2 个答案:

答案 0 :(得分:-1)

ES6 中,您可以使用对象解构

var obj = {
  "did": "00022B9A000000010001",
  "ps": -1,
  "hostName": "zs-dptpre-002.mr.corp.l.com",
  "ipAddress": "10.4.225.29"
}

var {did, ps, hostName, ipAddress} = obj;
console.log(hostName)

其他(非ES6)方式是使用Object.keys()forEach()循环并使用全局window对象为obj中的每个键创建变量

var obj = {
  "did": "00022B9A000000010001",
  "ps": -1,
  "hostName": "zs-dptpre-002.mr.corp.l.com",
  "ipAddress": "10.4.225.29"
}

Object.keys(obj).forEach(function(k) {
  window[k] = obj[k];
});

console.log(ipAddress);
console.log(did);

答案 1 :(得分:-1)

或者您可以使用JSONPath在JSON中使用Xpath类似的语法。有关此版本的详细信息,请参阅here。 在下面的示例中,我获取了所有对象属性值(叶子)。



////////////////////// JSONPATH
function jsonPath(obj,expr,arg){var P={resultType:arg&&arg.resultType||"VALUE",result:[],normalize:function(e){var t=[];return e.replace(/[\['](\??\(.*?\))[\]']/g,function(e,r){return"[#"+(t.push(r)-1)+"]"}).replace(/'?\.'?|\['?/g,";").replace(/;;;|;;/g,";..;").replace(/;$|'?\]|'$/g,"").replace(/#([0-9]+)/g,function(e,r){return t[r]})},asPath:function(e){for(var t=e.split(";"),r="$",a=1,n=t.length;n>a;a++)r+=/^[0-9*]+$/.test(t[a])?"["+t[a]+"]":"['"+t[a]+"']";return r},store:function(e,t){return e&&(P.result[P.result.length]="PATH"==P.resultType?P.asPath(e):t),!!e},trace:function(e,t,r){if(e){var a=e.split(";"),n=a.shift();if(a=a.join(";"),t&&t.hasOwnProperty(n))P.trace(a,t[n],r+";"+n);else if("*"===n)P.walk(n,a,t,r,function(e,t,r,a,n){P.trace(e+";"+r,a,n)});else if(".."===n)P.trace(a,t,r),P.walk(n,a,t,r,function(e,t,r,a,n){"object"==typeof a[e]&&P.trace("..;"+r,a[e],n+";"+e)});else if(/,/.test(n))for(var l=n.split(/'?,'?/),s=0,c=l.length;c>s;s++)P.trace(l[s]+";"+a,t,r);else/^\(.*?\)$/.test(n)?P.trace(P.eval(n,t,r.substr(r.lastIndexOf(";")+1))+";"+a,t,r):/^\?\(.*?\)$/.test(n)?P.walk(n,a,t,r,function(e,t,r,a,n){P.eval(t.replace(/^\?\((.*?)\)$/,"$1"),a[e],e)&&P.trace(e+";"+r,a,n)}):/^(-?[0-9]*):(-?[0-9]*):?([0-9]*)$/.test(n)&&P.slice(n,a,t,r)}else P.store(r,t)},walk:function(e,t,r,a,n){if(r instanceof Array)for(var l=0,s=r.length;s>l;l++)l in r&&n(l,e,t,r,a);else if("object"==typeof r)for(var c in r)r.hasOwnProperty(c)&&n(c,e,t,r,a)},slice:function(e,t,r,a){if(r instanceof Array){var n=r.length,l=0,s=n,c=1;e.replace(/^(-?[0-9]*):(-?[0-9]*):?(-?[0-9]*)$/g,function(e,t,r,a){l=parseInt(t||l),s=parseInt(r||s),c=parseInt(a||c)}),l=0>l?Math.max(0,l+n):Math.min(n,l),s=0>s?Math.max(0,s+n):Math.min(n,s);for(var o=l;s>o;o+=c)P.trace(o+";"+t,r,a)}},eval:function(x,_v,_vname){try{return $&&_v&&eval(x.replace(/@/g,"_v"))}catch(e){throw new SyntaxError("jsonPath: "+e.message+": "+x.replace(/@/g,"_v").replace(/\^/g,"_a"))}}},$=obj;return expr&&obj&&("VALUE"==P.resultType||"PATH"==P.resultType)?(P.trace(P.normalize(expr).replace(/^\$;/,""),obj,"$"),P.result.length?P.result:!1):void 0}

// some extensions I have added to JSONPath
var jsonPathStore = function(obj,path,values) {
 var maps=jsonPath(obj, path,{resultType:"PATH"})
 maps.map(function(item,index) {
  return eval( '(' + item.replace(/\$/,"obj") + '="' + values[index] +'"' + ')' );
 })
}


var jsonPathDelete = function(obj,path) {
 var maps=jsonPath(obj, path,{resultType:"PATH"})
 maps.map(function(item,index) {
  return eval( '(' + 'delete ' + item.replace(/\$/,"obj") + ')' );
 })
}
var jsonPathRead = function(obj,path) {
 var maps=jsonPath(obj, path,{resultType:"PATH"})
 return maps.map(function(item,index) {
  return eval( '(' + item.replace(/\$/,"obj") + ')' );
 })
}
////////////////////// JSONPATH

var data = {
  "did": "00022B9A000000010001",
   "ps": -1,
   "hostName": "zs-dptpre-002.mr.corp.l.com",
   "ipAddress": "10.4.225.29"
};

//
// xpath all leaf expression is //*[not(*)]
// in jspath becomes $..[?(@.length>=0)]
var jsonObjectLeafValues = 
    jsonPathRead(data,"$..[?(@.length>=0)]");

// this XPath will read all the id properties starting from the root element
console.log( JSON.stringify( jsonObjectLeafValues, null, 2 ) )