Is JSON equal to an Associative array?

Asked

Viewed 1,144 times

3

Are the two the same thing? Or is JSON a more complex library or technique?

  • JSON is a data format (such as XML, YAML, etc.). It can be used to serialize an associative array, resembling a Javascript object literal: { "chave":"valor", "outraChave":42, "outra":[1,2,3] }. But JSON is text, and can be produced/consumed by any language, not just Javascript.

  • @mgibsonbr Aah, it’s text. I got it. It’s kind of like XML with a programming language face.

2 answers

5


JSON is a standard for writing/formatting content in a string.
JSON stands for Javascript Object Notation but actually this format created by Douglas Crockford has been adapted by several languages and is today the standard format for sending content between applications and platforms.

So like YAML and XML JSON is plain text. The formatting rules are simple and the authority to check it is the http://jsonlint.com/. Basically:

  • Data is written in key/value pairs
  • The data are separated by vigulas
  • To refer objects is used {
  • To refer arrays is used [
  • The quotes used are double quotes "

So JSON is text and Arrays are language-specific and are dynamic representations of data with properties like length, index and others depending on the language.

Examples:

In Javascript to declare an array is made

var arr = ['foo', 'bar'];

The same JSON array would be a string:

var arrayJSON = '{ "arr": ["foo", "bar"]}';

Note that following the syntax of JSON we always have to give a key for each value. And to use Javascript would have to convert with the JSON.parse

var arr = JSON.parse(arrayJSON).arr;

To use the same array in JSON format in PHP you would have to do:

$arr = json_decode('{ "arr": ["foo", "bar"]}', true);
  • how can I chat with you?

2

It has nothing to do. JSON is one thing and an associative array is something else.

JSON stands for Javascript Object Notation, and is a kind of "Serialized Array", meaning you can generate it and carry it from place to place in string form, which makes it much easier to move data with this type of format. JSON is a subset of javascript and derivatives. (Reference)

An associative array, depending on the language, is a kind of dictionary, it has keys that can be strings and associate them with values, for example:

[URL] => Array ( [Chave] => [Valor] );

The difference is in the handling of both, while JSON can be "converted" into a common string, the array is an object that will need to be serialized in order to transport data, so it is easier to use JSON in some cases, the reading of the array is much simpler, which makes maintenance and support easier. But the Array is often used when you transpose values within the same application, because each language can have a different associative notation, unlike JSON, which is universal.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.