When to use dump vs. generate vs. to_json and load vs. parse in Ruby's JSON lib? -


The claim to David 4dev is that an object has a JSON string in json library: JSON. Dump (object) JSON.generate (object) object.to_json

and two equal methods to change a JSON string: Object

  JSON Loader (string) JSON.parse (string)   

But seeing the source code, each of them looks pretty different, and there are some differences between them (e.g.,).

What are the differences between them?

TL; DR: P> In general, use of to_json or equivalent generate , and parse Please.

For some special use cases, you want the dump or load , but it will load is unsafe to use.


Extended Explanation:

JSON :: Dump vs JSON :: generated

As part of the signature of its logic, JSON :: generate allows you to set options such as indented level and white location details . On the other hand, :: Generate inside, calls JSON :: dump with specific pre-set options, so you lose the ability to set it yourself Are there.

According to the docs, be the part of JSON :: dump of the Marshall :: Dump implementation plan is the main reason you explicitly : : You want to use Dump to stream your JSON data (for example on a socket), because : dump like you do the second argument Allows objects to pass. Unfortunately, the production of JSON data does not actually flow as is produced; It is composed collectively and JSON is completely built once. This makes an IO argument useful in trivial cases only.

The final difference between the two is that : dump can also take a boundary it increases the argument when a certain nest victim Goes deeper.


#to_json

#to_json objects as arguments , So the internal implementation is on one side, JSON :: generated (foo, opts) and foo.to_json (opts) are equivalent.


JSON :: load vs JSON :: parse

the same internal look To :: load call :: parse to internal :: dump calling :: generating :: Load , such as :: dump , can also take an IO object, but again, the source is read at a time, so streaming is limited to minor matters. However, contrary to both :: dump / :: generate dual, :: load and :: parse Accept the option as part of the signature of their argument.

: Load can also be passed, which will be called on every Ruby item to be parsed with data; It also comes with a warning that : Load should be used with reliable data only, there is no such restriction :: parse , and therefore JSON :: parse is the correct option for parsing untrusted data sources such as user input and files or streams with unknown content.

Comments

Popular posts from this blog

c - Mpirun hangs when mpi send and recieve is put in a loop -

python - Apply coupon to a customer's subscription based on non-stripe related actions on the site -

java - Unable to get JDBC connection in Spring application to MySQL -