获取json值作为字符串?

时间:2016-10-10 11:47:00

标签: javascript 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
}
*/

2 个答案:

答案 0 :(得分:0)

一般来说,没有。该信息无论如何都不存储。

如果代码是函数的一部分,那么你引用了该函数,你正在使用支持这种非标准功能的JS引擎,那么你可以调用thatfunction.toString(),然后尝试使用(例如)模式匹配找到相关的代码位。

答案 1 :(得分:0)

从设计的角度来看,这是一个非常糟糕的想法。

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

但是有一个丑陋的答案是肯定的,代价是依赖于使用 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 }
相关问题