0

I am confused by reading a lot of JSON tutorials on the Internet (even on STO) and not able to decide what is right and what is wrong related to writing an external JSON file.

I have seen so many instances e.g.

(for a single object tho Adobe Dreamweaver CS5.5 shows syntax error, don't know why)

#1

{
    "name" : "Sachin", 
    "age" : 30,
    "country" : "India"
}

#2

For multiple objects:

[
    {
        "name" : "Sachin", 
        "age" : 30,
        "country" : "India"
    },
    {
        "name" : "Amit", 
        "age" : 28,
        "country" : "USA"
    }
]

#3

Some have been seen using single quotes around the objects array and storing the array in a variable like this:

customers = '[
                {
                    "name" : "Sachin", 
                    "age" : 30,
                    "country" : "India"
                },
                {
                    "name" : "Amit", 
                    "age" : 28,
                    "country" : "USA"
                }
            ]'

#4

A few of them writing above code in the following style:

{
    "customers" : [
                    {
                        "name" : "Sachin", 
                        "age" : 30,
                        "country" : "India"
                    },
                    {
                        "name" : "Amit", 
                        "age" : 28,
                        "country" : "USA"
                    }
                  ]
}

#5

One more extra sample format added:

{
    [
        {
            "name" : "Sachin", 
            "age" : 30,
            "country" : "India"
        },
        {
            "name" : "Amit", 
            "age" : 28,
            "country" : "USA"
        }
    ]
}

To be honest, I am totally confused and can't figure out which one is correct and standard style for writing an external .json file (especially those having multiple objects).

So I am asking all my questions here:

  • What is the difference between all above formats? Using single quotes, storing the data in a variable or assigning a key to whole data etc.
  • How should I compose a correct formatted .json file which can easily be read by JavaScript and PHP?
  • In which standard format, the third parties APIs present json data?
Sachin
  • 1,646
  • 3
  • 22
  • 59
  • 2
    well the 1st , 2nd and 4th is valid json while the 3rd one is not valid json. – anees May 01 '20 at 19:05
  • For the 3rd: it is a JSON representation of data that is stored in a variable called `customers`, so the whole construct is not JSON, only the contents of the string is JSON. – t.niese May 01 '20 at 19:06
  • 1
    Since #3 isn't valid, for the rest there is for the most part no right way or wrong way. There is simply the best way for the available data and if you plan on having more data later on. Last one can be scaled the easiest and the second one works well if you have no plans on expanding to passing anything other than customer info – imvain2 May 01 '20 at 19:10
  • You are all telling me that sample #3 is NOT valid JSON data in an external .json file, right? Then please go and see this answer https://stackoverflow.com/a/24378510/5307298 where a user with good reputation score (high votes to his solution too) suggesting us to create a .json file with format identical to #3. Is he not explaining wrong and creating confusion to other users? – Sachin May 02 '20 at 04:39
  • I see you read the link I posted in my answer! The point is, that is not valid json format, but rather a technique to make it easier to read json data into javascript. You asked for a format that will work with javascript AND php, and that is pure json per the spec. If it's not valid json it won't pass validation, which is why your dreamweaver is complaining when it isn't pure json. – gview May 02 '20 at 20:59
  • @gview You are wrong! The #1 sample is pure valid JSON form but still AD is displaying syntax error. – Sachin May 04 '20 at 05:00
  • That may be true, but #3 is not valid JSON, which is the point. – gview May 05 '20 at 23:34

2 Answers2

0

What is the difference between all above formats? Using single quotes, storing the data in a variable or assigning a key to whole data etc.

You can't use variables in a JSON-file. The third example is probably some snippet of JSON being assigned to a variable within some application.

How should I compose a correct formatted .json file which can easily be read by JavaScript and PHP?

You can start and end the file with square brackets ([ ... ]) if you want to specify an array of multiple objects. If you start and end the file with curly brackets ({ ... }), you specify one top-level object (without a key).

However, you can embed arrays in objects, or include layers of objects. So your last example is indeed valid JSON. Read it as: a top level object, that itself has one attribute 'customers', which contains an array of more objects.

Lenny
  • 350
  • 1
  • 13
  • @Sachin He is creating confusion. The reason his example works is because of the way he loads the file. He is loading the JSON file as a JavaScript file. So the contents of the file will be read by the browser as JavaScript code. I just tried it myself, you can import a JSON file like that, an any JavaScript code in that file will be executed by the browser. I added a line (`alert('test');`) as the first line in the data.json file, it was executed by the browser. – Lenny May 02 '20 at 16:25
-2

As per its name: JSON = JavaScript Object Notation.

It deals with only 2 things:

  1. Javascript object(s) with any functions stripped out. An object can contain one or more name: value pairs, comma separated. Hopefully you can see that an object is denoted by the presence of { ... }

The JSON definition calls these name/value pairs 'members'. A member name has a colon after the name, so it can be represented as:

{ "name": value }

Value can be any basic javascript type, which are basically object, string, boolean, null OR an array. The safest way to do this so that's maximally interoperable/interchangeable is to always enclose the name in quotes, but it's not strictly necessary to be acceptable json.

So with several properties:

{
   "name": "Bob",
   "age": 3,
   "likes": ["eggs", "ham"],
   "parents": [{ "name": "Wilma"}, {"name": "Fred"],
   "deleted": false
}
  1. Javascript array

An array is an ordered (ie. 0..n) list of valid json types.

[ 3, "Hello", { "firstname": "Joe", "lastname": "Dimaggio" }, [ 0, 1, 2], true ]

In javascript, you can enclose a string using either single quotes or double quotes, but in json you must always use double quotes.

This won't pass json validation:

{ "name": 'Homer' }

That is all there is to it. An object has a name and a value that could be anything including another object or an array.

Objects are denoted with {} and arrays are denoted with []

Reading a static file is another issue entirely.

With PHP you use json_decode(). That's simple other than whether you want json objects to be turned into php objects, or nested associative arrays where the javascript object property names become the keys of the array. It defaults to making objects, and frequently that's more complicated than an array.

With Javascript often people just want to use the data easily, with the various issues and workarounds illustrated in the linked question.

gview
  • 14,876
  • 3
  • 46
  • 51
  • This is really misleading `{ name: value }` is not valid JSON, the same is for `[ 3, 'Hello',`. And `The safest way to do this so that's maximally interoperable/interchangeable is to always enclose the name in quotes, but it's not strictly necessary to be acceptable json.` is just wrong. In JSON keys must have double-quoted, and single quotes for strings are invalid. – t.niese May 01 '20 at 20:26
  • I misstated that, so I'm adjusting the response. To be clear my first example was not meant to be interpreted as json/javascript code, but just to re-state what is in the json manual. – gview May 02 '20 at 20:49