Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to parse json with YAML.load?

Tags:

json

ruby

yaml

I am using ruby 2.1.0

I have a json file. For example: test.json

    {
      "item":[
        {"apple": 1},
        {"banana": 2}
      ]
   }

Is it safe to load this file with YAML.load?

    YAML.load(File.read('test.json'))

I am trying to load a file which is in either json or yaml format.

like image 209
Niroj Shrestha Avatar asked Jul 07 '14 10:07

Niroj Shrestha


People also ask

Can a YAML parser parse JSON?

Since YAML is a superset of JSON, it can parse JSON with a YAML parser.

Why do people use YAML instead of JSON?

YAML extra features and concise notation makes it a good choice for configuration files (non-user provided files). JSON limited features, wide support, and faster parsing makes it a great choice for interoperability and user provided data.

Which one is better YAML or JSON?

JSON is comparatively faster than YAML. However, if data configurations are small then YAML is better since its interface is much more friendly. JSON has a feature to encode six different data types like an object, array, strings, numbers, null and boolean.


1 Answers

YAML can load JSON

YAML.load('{"something": "test", "other": 4 }')
=> {"something"=>"test", "other"=>4}

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

But generally the YAML construct is not JSON compliant.

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.

like image 76
Matt Avatar answered Sep 26 '22 17:09

Matt