-1

Could you please tell whether this is correct or wrong.

{{Id: "1", Name: "John"}, {Id: "2", Name: "BOB"}} --- > In doubt. Please confirm.

I always see formats like following placed in array. But can we also place the same in Object like above.

[{Id: "1", Name: "John"}, {Id: "2", Name: "BOB"}]  --- > This is correct
palaѕн
  • 72,112
  • 17
  • 116
  • 136
Chakra
  • 647
  • 1
  • 8
  • 16
  • 2
    Online JSON Validators: https://jsonlint.com/, https://jsonformatter.curiousconcept.com/, https://jsonformatter.org/. Tutorial: https://www.w3schools.com/js/js_json_intro.asp – Daniel Brose Apr 27 '20 at 06:21
  • 2
    The first format is incorrect. An object needs to have a key-value pair. – palaѕн Apr 27 '20 at 06:22
  • *can we also place the same in Object like above* **No**. Object is a key value pair. If you assign in that fashion, what will be the keys? How do you expect the compiler to iterate/ lookup to those – Rajesh Apr 27 '20 at 06:23
  • Maybe `{"1":{Id: "1", Name: "John"}, "2":{Id: "2", Name: "BOB"}}` is what you want. – Jack Ting Apr 27 '20 at 06:32
  • 3
    Please learn [the difference between JSON and the Object Literal Notation](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation). There is no JSON in your question. – str Apr 27 '20 at 06:42
  • Thanks everyone for your answers. – Chakra Apr 27 '20 at 07:27

2 Answers2

2

No, JSON Objects need a key. That is, they need something to identify them by.

Arrays don't need an explicit key because they are implicitly keyed by their position in the array. However, objects don't work the same way. As a quick illustration to demonstrate why, just remember that you can take the length of an Array, but not an Object.

Even if the JSON interpreter allowed this, how would you get the data out? It would be inaccessible.

There's no real reason to use objects like this anyways. That's what arrays are for. The only real difference is they're in square brackets.

AlgoRythm
  • 1,196
  • 10
  • 31
2

{..} is used in JSON to define a single instance and [..] is used to define a sequence of instances. To iterate or find one among multiple instance, JSON always needs a key and that is done by indexing through [..].