Sunday, September 8, 2013

Parsing JSON with keys that have the at sign or @ symbol

I had to work with this interesting JSON file which had a metadata section which can be accessed with @metadata key. Here's a small sample of the JSON file:

 "twitter_handle": "..........",
 "website": ".............",
 "@metadata": {
  "Access-Control-Allow-Credentials": "true",
  "Raven-Entity-Name": "4fff7413",
  "@id": "4fff7413-f1bd-4e00-ab51-6754f1111c03",
  "Last-Modified": "2013-09-08T08:29:35.2587326Z",
  "Raven-Last-Modified": "2013-09-08T08:29:35.2587326",
  "@etag": "01000000-0000-0003-0000-000000000001",
  "Non-Authoritative-Information": false
 }

The twitter_handle or the website data are just normal JSON values so they are not that interesting but the @metadata is where it gets interesting. How do you access that?

At first I tried object.@metadata, didn't work. So I tried the next one which is object[@metadata] which also didn't work. I then found out over at StackOverflow that I was quite near. All I had to do was put single quotes so it would look like object['@metadata'].

It also works if you're trying to get a value inside, like say @id within @metadata. It would end up looking like object['@metadata']['@id'].


No comments:

Post a Comment