简体   繁体   中英

How can I easily have a javascript function to parse out specific objects from json string

I would like to pull out each of these fields and put them into a their own variable in javascript

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

In ES6 you can use object destructuring

 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) 

Other (non ES6) way would be to use Object.keys() and forEach() loop and create variable for each key in obj using global window object

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

Or you could use a Xpath like syntax in JSON using JSONPath . See here for details about this version. In the following example I'm getting all object properties values (the leafs).

 ////////////////////// 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 ) ) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM