jsonajaxrestservice

Why and when to use JSON


I know what JSON is and what the advantages over XML. I already read some answers for this, but still I can't get through it.

So I would specifically ask this questions:

  1. Is it only useful for API thing? so exchange data without refresh the whole page using AJAX..
  2. Is it always used with AJAX?
  3. Do people (always/very often) using JSON like this? :: Database/Server - JSON - Client.. what I mean by that is, all our data from database will be put into JSON, so people can use it easily to any other platform/language?

Because from my point of view, if the data, which we need to output not much, why not just directly write on HTML directly, and if it's a lot of data, why not use database? If you don't mind, please add an example case to use JSON.


Solution

  • Because JSON is a lightweight data interchange format, it's uses vary widely. You describe using it for an API, which would be an idea situation to use JSON output over something like XML.

    To specifically answer your questions:

    1. It's not just useful for an API. It can be used to create configuration (for example, Composer's JSON configuration file). It can also be used for basic output to easily read with languages like JavaScript, since JSON is native to JavaScript as an object. (JavaScript Object Notation).
    2. It's not always used for AJAX. Say you were building a PHP application to convert currency, and you wanted to read from an API that output as JSON, this would always be preferred. Because languages like PHP have the ability to encode and decode JSON, you could read from the API (or other source) and decode it, giving you a PHP object or array of the JSON data.
    3. I think you mean reading from a database, outputting that in JSON format and then allowing clients to read it using an API. In this case, it's not always the way it's used - but if I had to guess, it's the most common way it's used, and probably most useful.