1

I've generated a JavaScript object (call it 'jItems') using $.getJSON. On the page, I've got a list of categories that the items in jItems fit into. My desire is to click a category and trigger a function to display only the items in that category. Would it be better to use getJson or jquery's each() or find() to pull the right items from jItems?

Michael Mior
  • 28,107
  • 9
  • 89
  • 113
Chris G.
  • 329
  • 4
  • 17
  • 1
    `getJson` pulls a JSON string from the server. Won't you need to use it either way? – pb2q Jul 30 '12 at 18:26
  • 1
    Store the results of a `getJSON` call, and then parse the parts you need on click... – TheZ Jul 30 '12 at 18:27
  • 1
    `.find()` is only for DOM elements. – gen_Eric Jul 30 '12 at 18:27
  • 2
    Note that there's no such thing as a "JSON object." JSON is a string representation commonly used to serialize JavaScript objects. Once it's been parsed (in JavaScript), it's a JavaScript object, not a JSON object. – Michael Mior Jul 30 '12 at 18:28
  • @TheZ `$.getJSON` parses the response automatically, so the callback receives an object value. There is no more parsing after that. – Šime Vidas Jul 30 '12 at 18:30
  • @Rocket It also work for XML trees. – Šime Vidas Jul 30 '12 at 18:30
  • @ŠimeVidas: True, but the OP has a JavaScript object, not XML. – gen_Eric Jul 30 '12 at 18:31
  • @ŠimeVidas From the sounds of it, the JSON that is returned has more data than each individual click needs so by parse I meant traverse. Sorry for the confusing word usage. – TheZ Jul 30 '12 at 18:31
  • 1
    @Rocket Most certainly. I was just responding to your comment that it only works for DOM elements. `:)` – Šime Vidas Jul 30 '12 at 18:33
  • Thanks for the clarification, I've used getJson to create a json "string" that we'll call "jItems". I was trying to ask the best way to extract the proper items when a category on the page is clicked- thereby dynamically rendering that categories items. looks like jqueries "each()" may be the best way. Sample json: [{"Category":"Dogs","Pic":"pic1.png","Item":"item 1","Desc":"dtext"}, {"Category":"Dogs","Pic":"pic2.png","Item":"item 2","Desc":"dtext"}, {"Category":"Cats","Pic":"pic3.png","Item":"item 3","Desc":"dtext"}, {"Category":"Cats","Pic":"pic4.png","Item":"item 4","Desc":"dtext"}] – Chris G. Jul 30 '12 at 19:05
  • @TheZ et al: Yes, my syntax was off as well. I too meant "traverse" – Chris G. Jul 30 '12 at 19:28

2 Answers2

1

The beauty of JSON is you don't need to parse it. It's already a JavaScript object. What you need to do is loop through the values and build the output for your category list.

Without seeing your JSON structure I cannot make any more recommendations.

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
  • 1
    You mean, the beauty of `$.getJSON`, right? (JSON is a string value. It needs to be parsed by `JSON.parse()` or an analogous function, in order to get the corresponding object value.) – Šime Vidas Jul 30 '12 at 18:35
  • 1
    That is only required if fetching via AJAX. JSON itself does not require this. – Diodeus - James MacFarlane Jul 30 '12 at 18:39
  • 3
    I think you're confusing JSON with JavaScript's object literal notation. Example: `var json = '{ "foo": 123 }'; var obj = { foo: 123 };`. JSON is, by definition, a string (value). It needs to, first, be parsed into an object value. If what you mean is not a string, then it's not JSON. – Šime Vidas Jul 30 '12 at 18:45
  • @nicerobot **1.** *"serialized JSON"* - that's the only type of JSON that exists. JSON is a serialized format by design. **2.** *"A JavaScript object literal can be JSON"* - While it is true that an object literal can *resemble* JSON (that's intentional), an object literal can never *be* JSON. **3.** *"But JSON is a JavaScript Object Literal!"* - Again, JSON does resemble an object literal, but *isn't* one. – Šime Vidas Feb 27 '13 at 14:41
  • @nicerobot JavaScript source code is text, but the parsed JavaScript program isn't. Therefore, object literals are text, but the resulting objects aren't. That being said, my point is that one should not confuse JSON with JavaScript object literals. JSON exists in separate-from-JavaScript environments (e.g. `.json` files), whereas object literals exist in JavaScript source code. **Note that within JavaScript source code, JSON can only appear within a string literal.** Object literals exist in JavaScript source code **outside** of string literals, so they cannot be JSON. – Šime Vidas Feb 28 '13 at 00:30
  • @nicerobot In that example, you're directly injecting the contents of a JSON file into a JavaScript program. As a result, the JSON *will* be parsed as an object literal. This just highlights that the same text can represent both JSON, and an object literal, depending on where it's located. One can do the opposite: copy-paste an object literal from JavaScript source code into a separate file and save it as a `.json` file. Now, the content of that file *is* JSON, even though it was an object literal before. So, what that text is, depends on where it's located, as my demo above points out. – Šime Vidas Feb 28 '13 at 02:12
  • @nicerobot There are two planes - the text plane (source code), and the object plane (in-memory). For instance, HTML exists in the text plane, so there is no such thing as an HTML object. When the browser parses the HTML code, a DOM tree is created. This tree exists in the memory of the browser, so we have DOM objects. Same concepts apply for JavaScript: we have JavaScript source code (text plane), and JavaScript programs (in-memory). My argument is that JSON exists in the text plane, and when it is parsed, the resulting object is *not* JSON. (I'm not even sure if I went off-topic with this.) – Šime Vidas Feb 28 '13 at 02:19
  • 1
    @ŠimeVidas JSON literals are to JavaScript as XML literals are to Scala. JSON can be represented natively in JavaScript as a native literal object. In exactly the same way that integer literals can exist in the language text and parsed into native structures. How it is parsed is not relevant. It is still textually EXACTLY JSON syntax in exactly the same way that XML literals in Scala are exactly XML even though the surrounding text isn't valid XML and even though the Scala compiler transforms the XML into native data structures. This is the last i will argue this. Good luck to you. – nicerobot Feb 28 '13 at 02:38
  • @nicerobot JSON and JavaScript object literals are **not** the same thing. Read here: [What is the difference between JSON and Object Literal Notation?](http://stackoverflow.com/q/2904131/425275). – Šime Vidas Feb 28 '13 at 13:43
  • @nicerobot Also, the official JSON web-site notes that: [*"JSON is a subset of the object literal notation of JavaScript."*](http://www.json.org/js.html). JSON is **not** the same thing as the JavaScript object literal notation; it's a restricted subset of it. – Šime Vidas Feb 28 '13 at 13:47
  • 1
    @ŠimeVidas If it quacks like a duck ... `{ "foo":"bar" }` is JSON. It is also a valid JavaScript literal. Therefore JSON literals are valid in JavaScript without having to be represented as strings! In fact, your prior comment states the same. A _subset_ means JSON **is** an object literal but object literals are more than JSON. Stop trying to put words in my mouth!!! I never said they were _the same_. Only that JSON is also a JavaScript object, and the json.org site agrees with me! This argument is over. You have shown that i am right! – nicerobot Feb 28 '13 at 18:51
  • @nicerobot As I already stated, it depends on the **context**. If `{ "foo":"bar" }` is the content of a `.json` file, then it's JSON. If however, it appears in a JavaScript program like so: `var obj = { "foo":"bar" };`, then it's **not** JSON, but an object literal. **I've asked in the [JS chat room](http://chat.stackoverflow.com/rooms/17/javascript), and my stance was confirmed by two other users: http://i.imgur.com/T4s6pVi.png**. Also notice how one of the users mentions that it *would* be JSON in another context. The same text *is* JSON in one context, but *isn't* JSON in another context. – Šime Vidas Feb 28 '13 at 20:20
  • 1
    @ŠimeVidas `1` is an integer literal and it doesn't matter where it resides nor how a compiler will interpret it!! `{"foo":"bar"}` is a JSON literal and it doesn't matter whether it's in a JavaScript file or any other file. In fact, even what i typed in this comment is JSON. I'm starting to suspect you're just pulling my leg that you don't understand this concept. So I give up. Good luck to you. – nicerobot Mar 01 '13 at 03:04
  • @nicerobot It matters because, when your so-called "JSON literal" appears in JavaScript code, then **the terminology changes**, and it's referred to as an "object literal" instead. Different environments define different terminology. In JavaScript source code the term "JSON literal" does not exist. The language does not define such a term. This is a fact. It is important for us as a community to **use correct terminology**. If we don't, we risk misunderstandings, which is **exactly** what happened in our argument. You demonstrated the risk of using incorrect terminology. – Šime Vidas Mar 01 '13 at 04:01
  • 1
    @ŠimeVidas No, you demonstrated your inability to manage multiple concepts simultaneously. A JSON literal in JavaScript is still JSON, _but_ it is **also** a JavaScript object literal. **They are both true!** And i've proven that your statement that _JSON can only be a string in JavaScript_ is false. JSON literals are valid syntax in JavaScript and it doesn't change from being valid JSON simply because it's in the context of JavaScript source code. I can extract it from the source code and put it, _exactly as is_, into a .json file and it is still JSON. You refuse to understand literals. – nicerobot Mar 02 '13 at 17:15
  • @ŠimeVidas What is `1.2345e67`? It's a floating point _literal_. It doesn't matter what type of file it's in, it's recognizable as a floating point number. Most languages interpret as such. It is no different than placing a JSON literal in JavaScript. JavaScript has native support for JSON literals so putting JSON into JavaScript doesn't change the fact that it is JSON. How JavaScript interprets it is irrelevant to the ability to use literals in the language. I get what you're think you're trying to do but you are simply _flat wrong_. – nicerobot Mar 02 '13 at 17:24
  • @nicerobot Unfortunately, you have for some reason decided to delete the first couple of your comments. (Why did you do that? Possibly, to remove evidence of incorrect statements you made in those comments?) I would have loved to be able to read them, to see how our argument began. Now, our argument cannot be resolved properly, as I don't have access to the full text of it. – Šime Vidas Mar 02 '13 at 18:46
  • @nicerobot I've invested hours in this conversation, knowing (well, at least I thought I knew) that the argument would be resolved, and we would come to an agreement. You have sabotaged that. See you on Stack Overflow. – Šime Vidas Mar 02 '13 at 19:29
  • @ŠimeVidas I deleted the comments in the hopes that it would discourage me from continuing with this pointless discussion. Clearly the strategy failed me. But trust me, my argument has not swayed from my original disagreement to your claim that "JSON is a string value." – nicerobot Mar 02 '13 at 22:18
  • @nicerobot OK, I think I've come to terms with your point of view. In the statement `var a = { "b": "c" };`, the part `{ "b": "c" }` indeed *is* JSON. This is where I have changed my mind. However, referring to it as JSON (instead of as an object literal) can be considered misleading (by some, including me). I've already shown you a screen shot above where I asked this exact question, and got two "No" answers. I just returned from another chat session, where I got another "No", and a "Yes, but it's misleading". So, while it *is* JSON, I will use the term "object literal" instead *exclusively*. – Šime Vidas Mar 02 '13 at 23:35
1

It all depends on how your data looks like but this might help you I think:

var jsonCats = [
    {"id": "category1", "items": [{"iid":"item1"}, {"iid":"item2"}, {"iid":"item3"}]},
    {"id": "category2", "items": [{"iid":"item4"}, {"iid":"item5"}, {"iid":"item6"}]},
    {"id": "category3", "items": [{"iid":"item7"}, {"iid":"item8"}, {"iid":"item9"}]},
    {"id": "category4", "items": [{"iid":"item0"}]}
];

$.each(jsonCats, function(key, value) {
    var category = $("<li>" + this.id + "</li>");
    var items = this.items;

    $("#categories").append(category);

    category.click(function() {
        $("#items").empty();
        for (var j in items) {
            var item = $("<option>" + items[j].iid + "</option>");

            $("#items").append(item);
        }
    });
});

To see an example: http://jsfiddle.net/tive/U63EY/

EDIT: Now I read your question again ... it's actually better to use for loops since this is faster. The $.each() is a wrapper of the for loop anyway. (Hence the example :D)

http://jsperf.com/jquery-each-vs-for-loop/6

Tim Vermaelen
  • 6,869
  • 1
  • 25
  • 39