使用YAML.load解析JSON是否安全? [英] Is it safe to parse json with YAML.load?
问题描述
我正在使用ruby 2.1.0
I am using ruby 2.1.0
我有一个json文件. 例如:test.json
I have a json file. For example: test.json
{
"item":[
{"apple": 1},
{"banana": 2}
]
}
使用YAML.load加载此文件安全吗?
Is it safe to load this file with YAML.load?
YAML.load(File.read('test.json'))
我正在尝试加载json或yaml格式的文件.
I am trying to load a file which is in either json or yaml format.
推荐答案
YAML可以加载JSON
YAML can load JSON
YAML.load('{"something": "test", "other": 4 }')
=> {"something"=>"test", "other"=>4}
JSON将无法加载YAML.
JSON will not be able to load YAML.
JSON.load("- something\n")
JSON::ParserError: 795: unexpected token at '- something'
会有一些晦涩的案例起作用,并产生不同的输出结果.
There will be some obscure cases that work and produce different output.
YAML.load("")
=> false
JSON.load("")
=> nil
但是通常,YAML构造不符合JSON.
But generally the YAML construct is not JSON compliant.
因此,请首先尝试JSON.load
,因为它可能更适合遮盖JSON内容.
捕获JSON::ParserError
错误并退回到YAML.load
.
So, try the JSON.load
first because it's probably better at obscure JSON things.
Catch the JSON::ParserError
error and fall back to YAML.load
.
这篇关于使用YAML.load解析JSON是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!