user3871
user3871

Reputation: 12718

using and storing json text in JavaScript

I'm making a 2D, top-down Zelda-style web single player rpg...

I'd like to store dialog in JSON format...

Currently I'm getting the json as an external javascript file. The json is stored as such in js/json.js:

function getJson() {

var json = {
    "people" : 
    [
        {//NPC 1 - rescue dog

etc...

Then I use it in my main game javascript file as such <script src="js/json.js"></script>..`

var json = getJson();

Then use it as such:

Labels[index].text = json.people[index].dialogs.start.texts[0];

Does it matter if I keep the json as a js file in a javascript function? Or should it be stored as a .txt file then parsed?

Thanks!

Upvotes: 1

Views: 198

Answers (2)

Raymond Zhou
Raymond Zhou

Reputation: 436

It's better off storing the data in pure JSON format and retrieving it via jQuery.getJSON() or an XMLHttpRequest, if you're using vanilla JavaScript. Otherwise, it looks like you're adding getJson() to the global scope, which may result in a conflict if you have another getJson() defined elsewhere.

So you could have a dialog.json that looks almost the same as what you have now, just without the unnecessary getJson() function:

{
    "people" : 
    [
        {//NPC 1 - rescue dog
         ...
        }
    ]
}

If you choose to use jQuery:

var dialog;
$.getJSON('json/dialog.json', function(data) {
    dialog = data;
    // Asynchronous success callback.
    // Now dialog contains the parsed contents of dialog.json.
    startGame();
});

Keeps your data separate from your logic.

Upvotes: 0

Anurag Uniyal
Anurag Uniyal

Reputation: 88757

It does not matter but JSON data is also JavaScript so store it as .js and later on you can add more data related functions to it if needed, btw your data file already has a getJSON function so it doesn't make sense to store it as .txt

On the other hand if an API is serving this data it need not have any extension at all.

Upvotes: 1

Related Questions