2.5.1 :007 > hash = {a: '1', b: '2', c: '3'}
=> {:a=>"1", :b=>"2", :c=>"3"}
2.5.1 :008 > hash.to_json
=> "{\"a\":\"1\",\"b\":\"2\",\"c\":\"3\"}"
2.5.1 :009 > hash.to_json.length
=> 25
2.5.1 :010 > JSON.dump(hash)
=> "{\"a\":\"1\",\"b\":\"2\",\"c\":\"3\"}"
2.5.1 :011 > JSON.dump(hash).length
=> 25
>>> import json
>>> dict = {'a': '1', 'b': '2', 'c': '3'}
>>> json.dumps(dict)
'{"a": "1", "b": "2", "c": "3"}'
>>> len(json.dumps(dict))
30
怎样用 ruby 得到和 python 同样得结果呢?
已经尝试过:
2.5.1 :015 > JSON.generate(hash, space: " ")
=> "{\"a\": \"1\",\"b\": \"2\",\"c\": \"3\"}"
2.5.1 :016 > JSON.generate(hash, space: " ").length
=> 28
# space: a string that is put after, a : or , delimiter (default: '')
ruby json string :
或 ,
后无空格
py json string :
或 ,
后存在空格