当我尝试在ruby(或http://json.parser.online.fr/)中解析以下JSON时,我收到错误,但我无法弄清楚原因。
要解析的JSON:
"{\"RED\"=>{\"t1\"=>0, \"t2\"=>2},
\"DANGEROUS_SITUATION\"=>{\"t1\"=>28, \"t2\"=>33},
\"SUB\"=>{\"t1\"=>1, \"t2\"=>0}, \"RED_CARS\"=>{\"t1\"=>0, \"t2\"=>0},
\"CRASH\"=>{\"t1\"=>10, \"t2\"=>6}, \"TRICKS\"=>{\"t1\"=>2,
\"t2\"=>3}, \"FREE_TRIES\"=>{\"t1\"=>9, \"t2\"=>5},
\"OWNERS\"=>{\"t1\"=>48, \"t2\"=>52}, \"ERRORS\"=>{\"t1\"=>5,
\"t2\"=>9}, \"YELLOW_CARS\"=>{\"t1\"=>0, \"t2\"=>0},
\"FANS\"=>{\"t1\"=>40, \"t2\"=>41}}"
编辑:如下面所述,这不是Json,而是一个字符串化的Ruby哈希,有没有办法将其转换为Ruby哈希?
答案 0 :(得分:2)
你这样做的最安全的方法是为火星gsub火箭然后解析字符串,即。
stringified_hash = "{\"RED\"=>{\"t1\"=>0, \"t2\"=>2}, \"DANGEROUS_SITUATION\"=>{\"t1\"=>28, \"t2\"=>33}, \"SUB\"=>{\"t1\"=>1, \"t2\"=>0}, \"RED_CARS\"=>{\"t1\"=>0, \"t2\"=>0}, \"CRASH\"=>{\"t1\"=>10, \"t2\"=>6}, \"TRICKS\"=>{\"t1\"=>2, \"t2\"=>3}, \"FREE_TRIES\"=>{\"t1\"=>9, \"t2\"=>5}, \"OWNERS\"=>{\"t1\"=>48, \"t2\"=>52}, \"ERRORS\"=>{\"t1\"=>5, \"t2\"=>9}, \"YELLOW_CARS\"=>{\"t1\"=>0, \"t2\"=>0}, \"FANS\"=>{\"t1\"=>40, \"t2\"=>41}}"
JSON.parse(stringified_hash.gsub('=>', ':')
你也可以eval将stringified_hash返回给Hash,然后调用.to_json,但如果字符串中有任何可评估的代码,则可以攻击
json = eval("{\"RED\"=>{\"t1\"=>0, \"t2\"=>2}, \"DANGEROUS_SITUATION\"=>{\"t1\"=>28, \"t2\"=>33}, \"SUB\"=>{\"t1\"=>1, \"t2\"=>0}, \"RED_CARS\"=>{\"t1\"=>0, \"t2\"=>0}, \"CRASH\"=>{\"t1\"=>10, \"t2\"=>6}, \"TRICKS\"=>{\"t1\"=>2, \"t2\"=>3}, \"FREE_TRIES\"=>{\"t1\"=>9, \"t2\"=>5}, \"OWNERS\"=>{\"t1\"=>48, \"t2\"=>52}, \"ERRORS\"=>{\"t1\"=>5, \"t2\"=>9}, \"YELLOW_CARS\"=>{\"t1\"=>0, \"t2\"=>0}, \"FANS\"=>{\"t1\"=>40, \"t2\"=>41}}").to_json
答案 1 :(得分:0)
预期的Json格式非常类似:
{
"RED":{"t1":0, "t2":2},
"DANGEROUS_SITUATION":{"t1":28, "t2":33},
"SUB":{"t1":1, "t2":0},
"RED_CARS":{"t1":0, "t2":0}
}