ohler55 / oj

Optimized JSON
http://www.ohler.com/oj
MIT License
3.14k stars 251 forks source link

So what should be done to avoid this in output #878

Closed kikonen closed 1 year ago

kikonen commented 1 year ago
h = { ...}
h.to_json
====>
{
  "date": {
    "json_class": "Date",
    "y": 2023,
    "m": 5,
    "d": 31,
    "sg": 2299161.0
  },
  "created_at": {
    "json_class": "Time",
    "s": 1683286844,
    "n": 928399000
  }
}

Have been trying different options, and seems that

Oj.add_to_json

causes output to be inapproriate.

Q: What flags should be toggled to get proper output.

config used:

require 'active_support'
require 'active_support/core_ext'

require 'json'

Oj.optimize_rails
Oj.mimic_JSON
Oj.add_to_json
kikonen commented 1 year ago

hmm...

p Oj.default_options

{:indent=>0, :second_precision=>3, :circular=>false, :class_cache=>true, :auto_define=>false, :symbol_keys=>false, :bigdecimal_as_decimal=>nil, :create_additions=>false, :use_to_json=>false, :use_to_hash=>false, :use_as_json=>false, :use_raw_json=>false, :nilnil=>false, :empty_string=>true, :allow_gc=>true, :quirks_mode=>true, :allow_invalid_unicode=>false, :allow_nan=>true, :trace=>false, :safe=>false, :float_precision=>16, :cache_str=>0, :ignore_under=>false, :cache_keys=>true, :mode=>:object, :integer_range=>nil, :escape_mode=>:json, :time_format=>:unix, :bigdecimal_load=>:auto, :compat_bigdecimal=>false, :create_id=>"json_class", :space=>nil, :space_before=>nil, :object_nl=>nil, :array_nl=>nil, :nan=>:auto, :omit_nil=>false, :hash_class=>nil, :array_class=>nil, :ignore=>nil}

so default mode is "object", not "compat" like I've expected

However,

Oj.default_options = {
  mode: :compat,
}

does not seem to fix it

kikonen commented 1 year ago

I guess my workaround is to not to add_json for Date/Time cases

I.e. just add other cases

Oj.add_to_json(Array, BigDecimal, Complex, Exception, Hash, Integer, OpenStruct, Range, Rational, Regexp, Struct)
ohler55 commented 1 year ago

I think that approach is exactly right.

ohler55 commented 1 year ago

Can this be closed?

kikonen commented 1 year ago

"Oj.add_to_json" resolved problem