0

For a standard JSON service, the content type is expected to be application/json (see What is the correct JSON content type?).

Since null, 123 or "foo" are valid JSON documents, any service producing application/json is alowed to return one of those as body.

What if I want to ensure that a service will return a valid JSON object or a valid JSON array?

Examples of valid objects

{}

or

{
  "foo": "bar"
}

Examples of invalid objects

123

or

null

or

[
  { "foo": "bar" }
]

(this one would be a valid array)

Alban Dericbourg
  • 1,484
  • 2
  • 15
  • 35
  • I'll wait for an expert to answer, but I guess there is no such thing. Since we're dealing with HTTP it's just text, I can send a response in XML format even if the client sends the "Accept" header as "application/json"(yes, that would be a bad practice). I guess the only way to ensure that is a valid JSON is validating the response on the client side. – Tom Melo Oct 05 '17 at 16:18
  • That is my first guess too. But I'm a bit lost in all the RFC, so in case of a surprise... – Alban Dericbourg Oct 05 '17 at 16:19

1 Answers1

0

You can use JSON Schema to define the expected responses, valid JSON documents and apply the strictness you wish to see in the incoming responses. And you can validate the incoming responses against the defined JSON schemas. There are many JSON Schema validators available open source. If you use node.js, jsonschema is a good module for it. You can be very strict in the JSON Schema definitions, like using additionalProperties: false etc.

Neeraj Sharma
  • 907
  • 6
  • 14