Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Ruby JSON parser ignore json_class?

I have a serialized JSON String (chef role definition actually) and it has a json_class key, making the ruby JSON parser try to force it to be a Chef::Role object. How can I make the parser ignore this key and just simply deserialize into a normal Hash?

like image 325
Randuin Avatar asked Feb 03 '11 01:02

Randuin


2 Answers

I just had the same problem, and found the answer by reading the source of the JSON gem - just unset JSON.create_id before trying to do the parse:

JSON.create_id = nil
JSON.parse('{ "json_class": "Chef::Role" }').class => Hash

EDIT: Note that since version 1.7 of the gem (1.8.0 is current as I type this update), the above hack is no longer necessary. JSON#parse now ignores json_class, and JSON#load should be used instead for unmarshalling dumped objects.

like image 178
Mark Reed Avatar answered Nov 07 '22 04:11

Mark Reed


The "json_class" key is there to indicate what Object the json should be un-marshaled as. It is added by JSON.dump. In more recent versions of JSON, JSON.parse will ignore "json_class", un-marshaling to a Hash. While JSON.load will un-marshal to the indicated Object (in your case, a Chef::Role).

JSON.parse('{ "json_class": "Chef::Role" }').class => Hash
JSON.load('{ "json_class": "Chef::Role" }').class => Chef::Role
like image 41
Matt Scilipoti Avatar answered Nov 07 '22 05:11

Matt Scilipoti