The Crystal Programming Language Forum

Adding a field to a json object

How can I add a field to a json object?
I have a json coming from a file (JSON.parse(file)) and I want to add (or update) a field to this json, but json[“my_field”] = does not work, nor json.put(“my_field”,…)

You can do it like this:

require "json"

json = JSON.parse(%({"foo": 1}))
json.as_h["bar"] = JSON::Any.new(2_i64)
puts json.to_json

It’s a bit cumbersome but there’s no other way because Crystal is statically typed.

We could consider adding more and more methods to JSON::Any, like []= but I don’t know.

Thank you for your answer, it’s working fine :slight_smile:
May be adding this to the json examples could be helpful for somebody.

Depending on what you’re doing, it might be worth looking into https://crystal-lang.org/api/master/JSON/Serializable.html. That would allow you to do:

struct MyObj
  include JSON::Serializable

  property foo : Int32
  property bar : Int64?
end

obj = MyObj.from_json %({"foo": 1})
obj.bar = 2_i64
obj.to_json # => {"foo":1,"bar":2}