# Adding a field to a json object

**URL:** <https://forum.crystal-lang.org/t/adding-a-field-to-a-json-object/1068>\
**Category:** Help & Support\
**Created:** [August 26, 2019, 11:16am UTC](https://forum.crystal-lang.org/t/adding-a-field-to-a-json-object/1068 "2019-08-26T11:16:02Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Guillaume](https://avatars.discourse-cdn.com/v4/letter/g/c67d28/32.png) [@Guillaume](https://forum.crystal-lang.org/u/Guillaume)\
**Post date:** [August 26, 2019, 11:16am UTC](https://forum.crystal-lang.org/t/adding-a-field-to-a-json-object/1068/1 "2019-08-26T11:16:02Z")

</div>

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”,…)

---

<div class="post-metadata">

**Author:** ![asterite](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/asterite/32/60_2.png) [@asterite](https://forum.crystal-lang.org/u/asterite)\
**Post date:** [August 26, 2019, 11:56am UTC](https://forum.crystal-lang.org/t/adding-a-field-to-a-json-object/1068/2 "2019-08-26T11:56:32Z")

</div>

You can do it like this:

```crystal
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.

---

<div class="post-metadata">

**Author:** ![Guillaume](https://avatars.discourse-cdn.com/v4/letter/g/c67d28/32.png) [@Guillaume](https://forum.crystal-lang.org/u/Guillaume)\
**Post date:** [August 26, 2019, 2:20pm UTC](https://forum.crystal-lang.org/t/adding-a-field-to-a-json-object/1068/3 "2019-08-26T14:20:41Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![Blacksmoke16](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/blacksmoke16/32/1241_2.png) [@Blacksmoke16](https://forum.crystal-lang.org/u/Blacksmoke16)\
**Post date:** [August 26, 2019, 2:30pm UTC](https://forum.crystal-lang.org/t/adding-a-field-to-a-json-object/1068/4 "2019-08-26T14:30:17Z")

</div>

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

```auto
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}

```
