-2

I was told that the reason I had to loop through JSON data is because JSON is an array. If that is true my question is why do you have to loop through JSON data in order to retrieve JSON Values? If that is not true is there another way to retrieve JSON data using jQuery? I added jQuery to my tag words because I would like to retrieve JSON data via jQuery. My JSON data is below:

    [  
       {  
          "input":0,
          "candidate":0,
          "delivery":"one",
          "last":"two",
          "point":"none",
          "fruit":{  
             "apples":"yes",
             "oranges":"no",
             "grapes":"yes",
          },
          "analysis":{  
             "code":"Y",
             "crr":"TTB",
          }
       }
    ]
Mariton
  • 601
  • 2
  • 12
  • 28
  • 3
    Your data is an array - and to find specific values in an array, you have to loop and find them (or use some array extension method, such as `find` - but under the hood that's just looping as well) - it's how arrays work. – tymeJV Dec 21 '17 at 16:22
  • 3
    JSON is a string representation of some data. That data may or may not contain an array or arrays. If you've been told that *"JSON is an array"* then you've been misinformed. – Reinstate Monica Cellio Dec 21 '17 at 16:24
  • JSON is just a formatted string not a JavaScript object. the example you have represents an array but it doesn't have to it would be valid to remove the square brackets `[]` and it would represent a single object. – phuzi Dec 21 '17 at 16:24
  • 1
    Have a look at [Access / process (nested) objects, arrays or JSON](https://stackoverflow.com/q/11922383/218196) – Felix Kling Dec 21 '17 at 16:28
  • That's like saying "my keys are on a table in the middle of my house, isn't there a way to get my keys directly without walking through the house?" – Jared Smith Dec 21 '17 at 16:30
  • @JaredSmith Actually it's not. I asked a valid question and I'm looking for a mature answer. Especially since I've learned all JSON data may not be an array. Please provide productive answers. – Mariton Dec 21 '17 at 16:36
  • @Mariton you are correct. Your question is actually more like asking "my keys are lost in my house, isn't there a way to retrieve them without searching my house?". JSON is a string. Not an array. Not an object. You can turn it into one of those things depending on its structure and whether or not it's well-formed. But once you get to that point, like any other data structure, unless you know ahead of time the exact structure and the exact path to the thing you want, you have to traverse the data structure to find it. – Jared Smith Dec 21 '17 at 16:40
  • 2
    @Mariton you're on the right track. What you shared above is an example of a JSON array (determined by the square brackets `[` and `]`). Attributes inside maps can be accessed without iteration (maps are denoted using curly brackets `{` and `}`). – rob Dec 21 '17 at 16:55
  • @JaredSmith I appreciate your answer but could you have just mentioned "JSON is a string. Not an array. Not an object." So I would get the understanding. A lot of these answers are helpful I just don't understand the purpose of mocking a question or giving an insulting answer in order to gain or get an advantage. But like I said thanks for your input – Mariton Dec 21 '17 at 18:15
  • 1
    @Mariton I'm not trying to mock or insult and I apologize if I gave that impression: I was trying to explain via analogy that your question has a flawed premise. To do a waaay deeper dive than is necessary, computers store memory at physical memory addresses. Think of your computers memory as a neighborhood, and skipping several layers of indirection, when you access an array index or an object property/hashtable key the computer accesses the memory stored in the block related to the array/object (think street) at the offset of the index/key (think address). So if you don't know the exact... – Jared Smith Dec 21 '17 at 20:29
  • ...address of the thing you want, you drive up and down the streets (iterate the data structure) until you find the thing you want. Usually when dealing with JSON you don't know the details ahead of time: once you parse it, it could be an object or an array, arbitrarily nested. There are some DSLs for querying nested data like for example XPath, but that's pretty advanced. Usually I just slog through it until I do or don't find what we're looking for: `var stuff = JSON.parse(json); Array.isArray(stuff) ? stuff.forEach(stuff => {...}) : Object.entries(stuff).forEach(([key, value]) => {...})` – Jared Smith Dec 21 '17 at 20:36
  • @JaredSmith Thank you. This explanation is very informative. Made sense – Mariton Dec 21 '17 at 20:46

1 Answers1

-6

JSON stands for JavaScript Object Notation.

In JavaScript Objects are Associative Arrays. Associative Arrays map unique keys (could be a string, but could also be a number) to a value.

Normal arrays are actually subsets of Associative Arrays (they have only* number keys). Where each (unique) number maps to a value.

To get all the data out of an array you ask it for the value of each key. This is usually done with a loop. In the case of Associative Arrays that means looping over its keys (whatever type they might be), and asking for its value in the array, like so:

for (var key in p) {
    if (p.hasOwnProperty(key)) {
        console.log(key + " -> " + p[key]);
    }
}

*Not completely true in JS, as length and some other things are actually also keys, which is also related to why you have to ask if a key is it's own property.

DhatGuy
  • 381
  • 3
  • 5
  • 1. Arrays and hashmaps are entirely different data structures, even in JavaScript. One is not a subset of the other. 2. Looping over an array with a `for..in` loop is asking for subtle bugs and has been considered bad practice for at least the last 6 years. – Jared Smith Dec 21 '17 at 16:43
  • https://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object – Kevin B Dec 21 '17 at 16:46
  • @JaredSmith I'm well aware that they are different data structures, but in general arrays are implementation in JS as special versions of hashmaps. For a couple of examples See the Mozilla Rhino implementation of an array at: [https://github.com/mozilla/rhino/blob/master/src/org/mozilla/javascript/NativeArray.java]. The comment on line 2121 describes the overall strategy, where dense arrays use an actual underlying array, but anything else uses HashTable storage. Spider Monkey at: [https://hg.mozilla.org/mozilla-central/file/tip/js/src/vm/NativeObject.h] takes a similar approach. – DhatGuy Apr 19 '18 at 13:51
  • @user602607 implementation details !== semantics. Or performance. Or aid in correctness. – Jared Smith Apr 19 '18 at 13:55
  • @JaredSmith although `for .. in` has its faults it is still the top answer when searching for 'how to iterate over an object', see: [https://stackoverflow.com/questions/14379274/how-to-iterate-over-a-javascript-object] – DhatGuy Apr 19 '18 at 13:55
  • @user602607 Wrong. See [this](https://stackoverflow.com/questions/5269757/why-is-javascripts-for-in-loop-not-recommended-for-arrays) question, [the one it's a dupe of](https://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea), etc. – Jared Smith Apr 19 '18 at 13:59
  • @JaredSmith you're right, while implementation details are not the same as semantics or performance they do help in understanding what's going on. Which is where I felt the OP had the most problems (understanding what's going on). Nevertheless, I admit that my answer is not great, and that I need to learn more about stackoverflow etiquette before proceeding any further. – DhatGuy Apr 19 '18 at 14:02
  • @user602607 indeed. If your answer (or question) garners six (6!) downvotes you should stop and try to understand *why* instead of entrenching your position. Would you have offered these arguments if I were your tech lead at work instead of a stranger on the internet? – Jared Smith Apr 19 '18 at 14:05
  • @JaredSmith I'm sorry, but the two threads you linked about `for .. in` are about why it's bad to use with an **array** while my answer (and the link I posted) is about iterating over an **object** – DhatGuy Apr 19 '18 at 14:06
  • @user602607 THE OP POSTED AN ARRAY. At least 6 people who saw this understood that and downvoted your answer. I am apparently just the one that is nice (read: stupid) enough to engage with you. – Jared Smith Apr 19 '18 at 14:11
  • 1
    @JaredSmith in all due respect, while I was clearly wrong, and am indeed reflecting on how to create proper answers... I also feel that conversation is healthy, and the only way to properly resolve misunderstandings. I would also bring up these points in a work environment. Thank you for your time, I will stop now. – DhatGuy Apr 19 '18 at 14:15