guyr79
guyr79

Reputation: 167

When would I prefer to use json over a query-string?

I stumbled upon a question which I can not find answer to in the internet: when would I prefer to use a JSON and when would I prefer to use a query-string?

would very much appreciate any further thoughts of yours experts on the topic.

Coded examples would be very much appreciated as well

Thanks!

Upvotes: 0

Views: 615

Answers (1)

freakish
freakish

Reputation: 56467

Let's make things straight:

  1. Query string is a fragment of URL that is after ? mark. For example in http://test.com/foo?baz=1 the fragment baz=1 is the query string for that URL.
  2. JSON is a well known data format. I won't dig here into the spec (since it is quite well known), but for example {"test":1} is a JSON string.

And so these are two different things. It is not like "this or that", for example you can combine both to have

http://test.com/?{"test":1}

And now you have JSON as a query string. Note that query string format is not standardized so this is completely valid.

So as you can see these two are not really comparable. Unless by "query string" you actually mean the concrete format, i.e. the typical x=1&y=2&z=3 style. These two we can compare. JSON has advantage of better structure, you can nest objects, you have arrays, you have (few but still) types. But it is less readable, especially since some characters in URL have to be escaped. And it takes a bit more time to parse it (unlikely to matter though).

My approach is as follows: for GET use "standard" query strings in URL, for POST JSON in body. If your GET becomes more complicated then turn it into a POST with JSON.

Upvotes: 1

Related Questions