2

我有一个很大的 JSON 字符串,我已将其编码为 javascript 对象。它看起来像这样:

{"stdout": "", 
"line": 23, 
"func_name": "<module>", 
"stack_to_render": [
    {"is_parent": true, 
    "ordered_varnames": ["__init__", "__qualname__", "num", "player", "__return__"], 
    "is_zombie": true, 
    "encoded_locals": {"__qualname__": "Team", "player": ["REF", 3], "__init__": ["REF", 2], "__return__": ["REF", 1], "num": 5}, 
    "frame_id": 1, 
    "unique_hash": "Team_f1_p_z", 
    "func_name": "Team", 
    "is_highlighted": false, 
    "parent_frame_id_list": []}], 
"ordered_globals": ["Team", "i_type", "s_type", "l_type", "t_type", "d_type",         "o_type", "make_squares"], 
"globals": {"s_type": "hello", 
    "o_type": ["REF", 8], 
    "l_type": ["REF", 5], 
    "make_squares": ["REF", 9], 
    "Team": ["REF", 4], 
    "d_type": ["REF", 7], 
    "i_type": 3, 
    "t_type": ["REF", 6]}, 
"heap": {"1": ["DICT", 
            ["__qualname__", "Team"], 
            ["player", ["REF", 3]], 
            ["__init__", ["REF", 2]], 
            ["num", 5]
          ], 
    "2": ["FUNCTION", "__init__(self)", 1], 
    "3": ["FUNCTION", "player(self, name)", 1], 
    "4": ["CLASS", "Team", [], ["__init__", ["REF", 2]], 
            ["__qualname__", "Team"], ["num", 5], ["player", ["REF", 3]]], 
    "5": ["LIST", 1, 2, 3, 4, 5, 6, 7, 8, 9], 
    "6": ["TUPLE", 2, 3], 
    "7": ["DICT", ["dictionary", 1]], 
    "8": ["INSTANCE", "Team", ["logo", null], ["members", 0]], 
    "9": ["FUNCTION", "make_squares(key, value)", null]}, 
"event": "return"}]}'

比方说,

var dict = "That dictionary ^^"

我有以下代码:

var name = dict.ordered_globals[i]; //Let's say returns "Team"

var ref = dict.globals.name;        
alert(ref[1]); //Should alert 4`

它抛出 undefined 因为字典中没有 .name 键值。我想要它做的就是把它dict.globals.name当作dict.globals.Team.

4

2 回答 2

3

你需要做:

var ref = dict.globals[name]

否则,name被视为文字键,而不是存储在name变量中的字符串。你想要后者。

于 2013-06-26T01:25:27.990 回答
0

如果您使用var ref = dict.globals.name;它将 视为name的属性之一dict.globals,但dict.globals根本没有该name属性,以防您想检索对象的属性但您不知道确切的属性名称,或者它可以是在运行时更改,如果是这种情况,那么文字键就派上用场了var ref = dict.globals[name]。希望这有帮助

于 2013-06-26T02:17:45.647 回答