使用YAML.load解析JSON是否安全? [英] Is it safe to parse json with YAML.load?

查看:425
本文介绍了使用YAML.load解析JSON是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆