Utilizing and saving JSON data in JavaScript

I am currently working on developing a 2D, top-down RPG game inspired by Zelda for the web...

My plan is to organize dialog in JSON format...

Right now, I have the JSON data stored in an external JavaScript file called js/json.js:

function getJson() {

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

etc...

To access this data in my main game JavaScript file, I include it using

<script src="js/json.js"></script>
..`

var json = getJson();

Then, I can reference the data like this:

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

I'm wondering if there would be any benefit to storing the JSON as a separate .txt file and then parsing it instead of keeping it as a JS file within a function.

Any insights would be greatly appreciated!

Answer ā„–1

Storing JSON data as a .js file allows for additional JavaScript functions to be added later if necessary, since JSON is essentially JavaScript. It's worth noting that the existing data file already includes a getJSON function, so storing it as a .txt file wouldn't be logical.

However, when data is being served through an API, there is no requirement for any file extension at all.

Answer ā„–2

When you're working with JavaScript, it's recommended to store your data in a pure JSON format and access it using jQuery.getJSON() or an XMLHttpRequest. This approach helps prevent conflicts by not adding unnecessary functions like getJson() to the global scope.

For example, you can have a file named dialog.json structured similar to your current setup but without the extra getJson() function:

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

If you opt for jQuery, you can load the JSON data like this:

var dialog;
$.getJSON('json/dialog.json', function(data) {
    dialog = data;
    // Once the data is loaded, you can use it in your application.
    startGame();
});

By keeping your data separate from your code, you maintain better organization and reduce the risk of conflicts.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to create a selection input using buttons and save the chosen option in the state?

Check out this snippet showcasing 3 buttons const [role, setRole] = React.useState('') const [active, setActive] = React.useState(false) <Grid container spacing={1}> <Grid item xs={4}> <Button variant='plain&apos ...

How can you utilize jq to retrieve values from a JSON array that have a specific key with a boolean value of true

Here is a JSON data structure: [ { 'id': 'something', 'isSparse': true }, ... ] I'm looking to extract the IDs of entries where isSparse == true using a jq command. How can I achieve this? I attempted the ...

Tips for composing a single aggregation within a query

In my query, I wanted to find the first record with a CREATE_DATE greater than or equal to a specific date and less than another date. After calculating the duration between these dates, I needed to write another query. However, I was unsure how to combine ...

Sending a null JSON string in C# using HttpWebResponse

I'm really struggling with this issue. I have a Web API handler for POST that I can't seem to get working correctly: [HttpPost] public IActionResult Post([FromBody]string jsonString) { if (jsonString == null) retu ...

Guide to using jquery-throttle-debounce with addEventListener

I'm feeling a bit lost and confused, so I'm attempting to simply "imitate what I see without truly understanding what I'm doing"... <script> // This example is functional: $window.scroll($.throttle(50, function(event) { // some ac ...

Accessing a particular node in JSON using PHP's JSONPath function

Here is the structure of my JSON data: { "Photos":{ "Photo":[ { "ID" : 111, "type" : "JPEG", "URL": "blabla" }, { "ID": 222, ...

Styling Your Navigation Bar with CSS and Active States

Creating an interactive navigation element for a menu can be challenging, but here's a helpful example. http://jsfiddle.net/6nEB6/38/ <ul> <li><a href="" title="Home">Home</a></li> <li class="activ ...

The function ng-click does not successfully uncheck ion-radio

In the process of developing my application using the ionic framework, I encountered a challenge where I needed to deselect an ion-radio button when clicking on an input tag. Despite attempting to achieve this functionality through this ionic play link, I ...

Get ready for 10 AM with the RxJS timer function

I am trying to figure out how to schedule a method in my code using rxjs/timer. Specifically, I want the method to run at precisely 10 AM after an initial delay of 1 minute. However, my current implementation is running every 2 minutes after a 1-minute d ...

Determining the position of a v-for element in Vue.js when making an HTTP request

I'm faced with a challenge involving an array of posts with comments, each post having an input for creating a new comment. The posts array contains the id of each post as a prop, but I'm unsure how to select the specific post for which I want to ...

Angular $mdDialog allowing for multiple instances to be created

Working with modal tabs, I have a notification pop-up window that is always displayed to the user upon logging into my application. This pop-up contains all events that occurred while the user was offline. The issue arises when clicking on any object from ...

Tips for sending arguments to an async function

I am currently facing an issue in my vue.js application where I am struggling to access the value of name that is being passed to my function. My hunch is that this issue is related to scope. After some research, it seems like using a fat arrow function mi ...

Transform a React component from a regular function to an ES6 class

Recently delving into ES6 and React, I found myself navigating through various ways to write a React component. My journey began with "React.createClass," then transitioned to utilizing "extends React.Component" with ES6 classes syntax. While following a ...

Initial button click fails to trigger onclick event

After researching and reading various articles on the issue, I have tried several solutions but nothing seems to work. The problem occurs when the button is clicked for the first time - nothing happens. It is only after clicking the button a second time th ...

What methods are available for implementing animated hiding and showing of elements?

With the recent removal of jQuery in Bootstrap 5, I am revisiting a project to make it more lightweight by using standard JS. One part of the project involves implementing a transition effect that previously used jQuery: $('#form-1').hide('s ...

Error: Failed to parse the given color specification

My chrome extension is showing an error message: Unchecked runtime.lastError: The color specification could not be parsed. This error seems to be in the popup.html: 1 -> <! DOCTYPE html> line. Can anyone explain what this means and how to fix ...

Looking for a way to implement a vertical autoscroll <ul> list that responds to mouse movement using JavaScript and jQuery

Could you assist me in enabling the list items to be moved using mouse movement? When the user moves the mouse cursor vertically upward over the list, the list should scroll downward. If the user moves the mouse cursor downward over the list, the list shou ...

Menu is not functioning properly as it is not staying fixed in place

I am trying to create a fixed menu that sticks to the browser window as it scrolls. However, I am encountering an issue where the transition from sticky to fixed is not smooth when I remove position: relative; from navbar__box. window.onscroll = functio ...

Using Javascript/JQuery to apply pixel values in CSS styling

Recently, I've come across a discrepancy between two different ways of accessing CSS properties in jQuery: <foo>.css('marginTop') (which I always assumed was the standard notation) and <foo>.css('margin-top') (which ...

Setting a new state versus modifying the existing state by using setState have distinct nuances

Iā€™m currently struggling with updating the value of a specific key in the state of my component. The state is structured as follows: this.state = { stateValue1: false, stateValue2: false, stateValue3: false }; To update the ...