0

How to use a JSON string(pretty large) as a database for HTML5

I know we can use localStorage.setItem('key',value) for storing a specific value.Im having a JSON string that contains 200 to 300 records

[{"key":"value"....},
{"key":"value"....},
{"key":"value"....},
......
.....
...
//around 300
]

Right now im putting this entire JSON in a div with display said to none and accessing that JSON like this

$.parseJSON($('#mydivid').html());

Any other alternate suggestion ? Thank you

4
  • Why don't you use directly the localStorage with localStorage['key'] ? Why use a div ? Commented Sep 21, 2012 at 10:54
  • @dystroy Please see my requirement..im having a big JSON Commented Sep 21, 2012 at 10:55
  • Where is it coming from ? And why the div ? Commented Sep 21, 2012 at 10:56
  • Actually its a entire database encoded using php 's json_encode function.. Commented Sep 21, 2012 at 10:58

1 Answer 1

1

I'm not sure I understand the problem.

Supposing you have a json file (many MB if you like) generated by your server, you can fetch it with a simple ajax query, parse it, and then use it as

var myval = database['somekey'];

You shouldn't wrap it in your html, it prevents the normal caching of your page if only the database changes.

Your json would be stored or generated in a second separate .json file (that you can very well generate in PHP).

The function to fetch it would look like this :

var database;

function fetchDatabse(callback) {
    var httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = function() {
        if (httpRequest.readyState === 4) {
            if (httpRequest.status === 200) {
                database = eval('('+httpRequest.responseText+')');
                if (callback) callback();
            }
        }
    };
    httpRequest.open('GET', 'database.json?time='+(new Date().getTime()));
    httpRequest.send(); 
}

Note that it's usually better to fetch only parts of a database using ajax queries.


If you really want to embbed your json in your page, instead of embedding it in a hidden div, embedd it in a script :

<script>
var database = {
   ...
};
</script>
Sign up to request clarification or add additional context in comments.

4 Comments

Where do i store the json for accessing it..?
Here's an exemple : dystroy.org/re7210 the html page queries the recipes database which is defined in a json file.
let me check..thanks..this works like a charm i know..but things are different when the app becomes offline..i cant find the external json
You want your webapp to be available offline ? Have a look at this if you really think this is an important requirement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.