views:

143

answers:

1

Hi,

Here's something I want to learn and do. I have a JSON file that contains my product and details (size, color, description). In the website I can't use PHP and MySQL, I can only use Javascript and HTML. Now what I want to happen is using JQuery I can read and write a JSON file (JSON file will serve as my database). I am not sure if it can be done using only JQuery and JSON.

  1. First thing, How to query a JSON file? (Example: I would search for the name and color of the product.)

  2. How to parse the JSON datas that were searched into an HTML?

  3. How to add details, product to the JSON file?

It will also be great if you can point me to a good tutorial about my questions.

I'm new to both JQuery and JSON.

Thanks!

+5  A: 

Since Javascript is client side, you won't be able to write to the JSON file on the server using only Javascript. You would need some server side code in order to do that.

Reading and parsing the JSON file is not a problem though. You would use the jQuery.getJSON function. You would supply both a url and a callback parameter (data isn't needed, because you're reading a file, so no need to send data). The url would be the path to your JSON file, and the callback would be a function that uses the data.

Here's an example of what your code might look like. I don't know exactly what your JSON is, but if you have a set called "products" containing a set of objects with the details "name" and "price", this code would print those out:

$.getJSON("getProductJSON.htm",
    function(data) {
        $.each(data.products, function(i, item) {
            var name = item.name;
            var price = item.price;
            // now display the name and price on the page here!
        });
    }, 
);

Basically, the data variable in $.getJSON makes the entire contents of the JSON available to you, very easily. And the $.each is used to loop over a set of JSON objects.

Kaleb Brasee
Thanks Kaleb Brasee!
Pennf0lio