YAWS json vs json2

Have a Erlang YAWS project that uses the json/json2 modules?  Notice some weirdness after upgrading to json2?  Yep , me too.

In the original json you might do something like this:

case json:decode_string(JSONdata) of
  {ok, {struct, Data}} ->
    [Field1,Field2] = [
      proplists:get_value(X, Data) || X <- [field1,field2]

in order to access the values in a JSON object that you have decoded.  field1/2 are the key names in your object and Field1/2 are the variables that the values of those fields get stored in.

However, if you are like me and think that the behaviour of such a fundamental function like decode_string/1 wouldn’t change between versions, think again!  It does!

Just change json:decode_string(JSONdata) to json2:decode_string(JSONdata) and your app will break.  Field1 and Field2 will be undefined rather than containing the values that you expect.

While I don’t know why it changed (probably something to do with barewords) what I do know is how to fix it:

case json2:decode_string(JSONdata) of
  {ok, {struct, Data}} ->
    [Field1,Field2] = [
      proplists:get_value(X, Data) || X <- ["field1","field2"]

That’s right.  You just need to quote the field names now.  Easy.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s