KyleHQ

Honest, loyal, senior software engineer, looking to make a real difference by putting people first.

KyleHQ © 2024

What JSON?

December 31, 2016
|
code

If you’re one to consume JSON api’s (who isn’t really?), then it’s likely you’ve bumped into the issue of figuring out whether the resource you just called is returning a single JSON object or an array payload. As per the JSON API Spec,

The document’s “primary data” is a representation of the resource
or collection of resources targeted by a request.

Primary data MUST be either:

a single resource object, a single resource identifier object, or null, for requests that target single resources

an array of resource objects, an array of resource identifier objects, or an empty array ([]), for requests that target resource collections

To help out all the Gophers out there, I created a simple little helper package to figure it out for you.

Checkout the code here https://gitlab.com/kylehqcom/whatjson.

It’s pretty simple really, so instead of having a dependency to my repo, just copy paste into your project instead.

Usage

Just call WhatJSON() with a body of type []byte and an optional prefix. The code will check the very next char after the prefix has been matched to determine whether the body is a object or an array. Go check out the code already!

Short n sweet, enjoy =]