获取json值作为字符串?

问题描述:

说我有一个对象获取json值作为字符串?

var BOB = { 
"name": "bob", 
"height": 185 
}; 

而且我还有一个目标,从它

var PROPS = { 
"bob": { 
    "height": BOB.height 
}; 

引用值所以现在PROPS.bob.height将等于185。如果我字符串化的对象,我得到

{"bob": {"height": 185}} 

我能计算出的什么评价返回值185字符串值。例如从代码中计算源代码...:

var s = findOutTheSourceCode(PROPS); 

// s would be 
/* 
{ 
"bob": { 
    "height": BOB.height 
} 
*/ 
+1

不,你不能! – adeneo

+1

你能解释你想达到什么吗? – Rajesh

+0

您可以遍历所有对象属性以查找路径。但它只适用于价值唯一的情况下 – k102

一般来说,没有。无论如何,这些信息都不会被存储。


如果代码是一个功能你必须是功能您使用支持该非标准功能,那么一个JS引擎的引用的一部分,您可以拨打thatfunction.toString(),然后尝试使用(例如)模式匹配找到相关的代码位。

这是一个真的很差想法从设计角度。

无论如何,回答你的问题,简短的回答是“不,你不能”。

但有一个丑陋回答说是,在依靠使用EVAL这是一个更坏主意的成本。例如:

var BOB = { 
"name": "bob", 
"height": 185 
}; 

var PROPS_src = '{\n' 
    + ' "bob": {\n' 
    + ' "height": BOB.height\n' 
    + ' }' 
    + '}'; 

eval('var PROPS = '+PROPS_src); 

console.log("PROPS_SRC:__________________"); 
console.log(PROPS_src); 
console.log("PROPS:______________________"); 
console.log(PROPS); 

// Output: 
// PROPS_SRC:__________________ 
// { 
// "bob": { 
//  "height": BOB.height 
// }} 
// PROPS:______________________ 
// { bob: { height: 185 } } 

但是,正如我所说,这一切是非常糟糕的主意。我几乎不建议你重新设计你的数据结构(和需要的代码),以一种可以追踪数据源的方式。

对于(快速和肮脏的)例子:

var people = { 
    bob: { 
    "name": "bob", 
    "height": 185 
    } 
}; 

var props = { 
    "bob": { 
    "someConstant": "Hello World", 
    "_height": "height", 
    } 
}; 

function getProps(who){ 
    var out = {}; 
    Object.keys(props[who]).map(function(k){ 
     if (k.substring(0,1) == "_") { 
      out[k.substring(1)] = people[who][props[who][k]]; 
     } else { 
      out[k] = props[who][k]; 
     }; 
    }); 
    return out; 
}; 

console.log("Raw:", props['bob']); 
console.log("Calculated:", getProps('bob')); 

// Output: 
// Raw: { someConstant: 'Hello World', _height: 'height' } 
// Calculated: { someConstant: 'Hello World', height: 185 }