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

coolguy
  • 7,866
  • 9
  • 45
  • 71

1 Answers1

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>
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • Where do i store the json for accessing it..? – coolguy Sep 21 '12 at 10:59
  • Here's an exemple : http://dystroy.org/re7210/ the html page queries the recipes database which is defined in a json file. – Denys Séguret Sep 21 '12 at 11:00
  • 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 – coolguy Sep 21 '12 at 11:04
  • You want your webapp to be available offline ? Have a look at [this](http://html5doctor.com/go-offline-with-application-cache/) if you **really** think this is an important requirement. – Denys Séguret Sep 21 '12 at 11:06