简体   繁体   中英

How to structure and parse JSON

I'm creating a web RPG using HTML5 and JavaScript embedded directly into my website. The game will be a single player game against computer opponents... the design will be top-down 2D, Zelda style. It will be real time, but conversing with computer players will be scripted... they say something, and you're given some response options.

I was thinking of writing the dialog in XML, but I was told I should use JSON as it's easier to parse using JavaScript.

I saw Abstract Chaos' answer in XML...

<?xml version="1.0" encoding="UTF-8"?>
    <npcs>
      <npc name="Abstract">
        <dialogue>
          <text>Welcome #{PlayerName} to Stack Exchange, What would you like to know? </text>
          <options>
            <option action="dialogue5">Tell me about Stack Exchange?</option>
            <option action="quest1">Give me quest</option>
            <option action="object1">Give me object</option>
          </options>
        </dialogue>
        <dialogue id="5">
          <text>Stack Exchange is a fast-growing network of 87 question and answer sites on diverse topics</text>
          <text>We build libraries of high-quality questions and answers, focused on the most important topics in each area of expertise</text>
        </dialogue>
      </npc>
    </npcs>

And was wondering how I could achieve the same sort of layout in JSON...

My questions are:

  • How can I layout RPG dialog scripts in JSON to be parsed by JavaScript?
  • Can I have an example of how I could use JavaScript logic to parse JSON given certain conditions (ex: NPC asks question: "Can you help me?", JSON should have options "Yes" and "No", which could be based on if the player actually has that skill set to help).
  • The JSON dialog text will be stored in a separate "dialog" folder in my project folder... so it will need to be accessed externally

The only thing I've found on how to layout and parse JSON is:

        var json = '{"result":true,"count":1}',
            obj = JSON && JSON.parse(json) || $.parseJSON(json);

        alert(obj.result);

But it doesn't have the neatness factor that XML seems to have.

Any help would be appreciated...

Thanks!


Trying to load and alert external JSON text file doesn't work:

HTML:

<html>
    <head>
        <title>Working with JSON</title>
        <script src="jquery.js"></script>
        <script>
            (function() {

            var data = "/JSON_TEXT.txt";    

            var first_q = data.npcs[0].dialogs[0];
            alert(first_q.text);

            }());
        </script>

    </head>
    <body>
    </body>
</html>

JSON plain text file : JSON_TEXT.txt

'npcs': [
            {
                'name': 'Abstract',
                'dialogs': [
                    {
                        'text': 'Welcome',
                        'options': [
                            'df', 'f'
                        ]
                    }
                ]
            }
        ]

How can I layout RPG dialog scripts in JSON ?

The equivalent of the XML you gave us would be (without the comments):

// you might use a top wrapper object with a property "npcs" for this array
[
    {
        "name": "Abstract",
        "dialogues": {
// I recommend on object with dialogues by id instead of an array
             "start": {
                 "texts": [
                     "Welcome #{PlayerName} to Stack Exchange, What would you like to know?"
                 ],
                 "options": [
                     {
                         "action": "dialogue 5",
                         "text": "Tell me about Stack Exchange?"
                     }, {
                         "action": "quest 1",
                         "text": "Give me quest"
                     }, {
                         "action": "object 1",
                         "text": "Give me object"
                     }
                 ]
             },
             "5": {
                 "texts": [
                      "Stack Exchange is a fast-growing network of 87 question and answer sites on diverse topics",
                      "We build libraries of high-quality questions and answers, focused on the most important topics in each area of expertise"
                 ]
             }
         }
         // further properties of the NPC like objects and quests maybe
    },
    … // further NPCs
]

How to parse JSON?

See Parse JSON in JavaScript? .

 var json = {…}; var data = JSON && JSON.parse(json) || $.parseJSON(json); 

Ouch, no! That's no JSON, that's just an object literal in JavaScript. You can use it like

var data = {…};

and data will be your object. You need to parse JSON only when you have it as a string, for example when you've loaded a file via ajax.

JavaScript logic to parse JSON given certain conditions

That's your game logic, with which we can't help you. But you don't need to parse JSON there, you only need to access the data which you have already parsed. See Access / process (nested) objects, arrays or JSON for that.

Some find JSON harder to read than XML. I think it's much cleaner and easier to use, especially if you want to parse it with JS.

That said, I'm not really sure what your question is—you already have the data in XML, so just convert it to JSON. You can use arrays ( [] ) for lists and objects ( {} ) for when you need named keys:

{
    'npcs': [
        {
            'name': 'Abstract',
            'dialogs': [
                {
                    'text': 'Welcome #{PlayerName} to Stack Exchange, What would you like to know?',
                    'options': [
                        //options here
                    ]
                },
                //next dialog object here
            ]
        },
        //next npc object here
    ]
}

So, like you said, first you'll need to parse the JSON string:

var json; //contains the json string, perhaps retrieved from a URL via AJAX
data = JSON && JSON.parse(json) || $.parseJSON(json);

You could also assign the JSON object to a JS variable in the first place (say, in a .js file somewhere) and you won't need to parse at all. Just be sure not to pollute the global scope.

After parsing, data is a normal JS object. You can access its properties just like any other object. So, to access the first question from the first NPC, do:

var first_question = data.npcs[0].dialogs[0];

Let's alert the question itself:

alert(first_question.text);

You can access its options like this:

first_question.options;

You asked about how to load the JSON data from an external file. The usual approach is to load the file's URL via AJAX. Here is a nice tutorial for making AJAX requests with vanilla JavaScript: https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started

But there's not much reason to hand-code AJAX requests with vanilla JavaScript. I recommend using a library like jQuery , which has handy AJAX functions such as .ajax and the shorthand function .get . Here's an example using .get :

var data;                          //will hold the parsed JSON object
var json_url = 'json.txt';         //URL of your JSON (just a plain text file)
$.get(json_url, function(json) {
    data = JSON && JSON.parse(json) || $.parseJSON(json);
});

//use data here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM