How to structure and parse JSON - javascript

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

Related

How to correctly parse the JSON?

I have developed a Cordova android plugin for my library. The library is used for sending events across different connected devices.
JS interface receives a JSON from the java side. What I want to do is to parse this before reaching the application so that the developer can directly use it as a JS object. When I tried to parse the JSON in my plugin's JS interface, I am running into issues. Below is an example:
Received by JS interface:
{"key":"name","data":"{\"name\":\"neil\",\"age\":2,\"address\":\"2 Hill St\"}"}
After parsing in JS interface:
Object {key: "name", data: "{"name":"neil","age":2,"address":"2 Hill St"}"}
data:"{"name":"neil","age":2,"address":"2 Hill St"}"
key:"name"
__proto__:Object
As you can see, if this data reaches the app and the developer accesses the data:
eventData.key = name;
eventData.data = {"name":"neil","age":2,"address":"2 Hill St"};
eventData.data.name = undefined
How can I parse the inner data as well in my JS interface so that the developer can access directly. In the above case, he has to parse eventData.data to access the properties. I don't want this to happen and I want to do this in JS interface itself.
Please note that eventData can have many properties and hence they should be properly parsed before passing into the app.
I am new to Javascript and hence finding it difficult to understand the problem.
It seems that your returned JSON contains a string for the data property.
var response = {"key":"name","data":"{\"name\":\"neil\",\"age\":2,\"address\":\"2 Hill St\"}"};
//Parse the data
var jsonData = JSON.parse(response.data);
console.log(jsonData.name); //neil
console.log(jsonData.age); //2
console.log(jsonData.address);//"2 Hill St"
As others pointed out, you have to do JSON.parse(eventData.data) as the data comes as a string.
You have to look why that happens. The inner data might be stored in this way, in some cases its valid to store it in db as flat object or it is stringified twice by mistake:
var innerdata = JSON.stringify({ name: "neil" });
var eventData = JSON.stringify({ key: "name", data: innerdata });
would correspond to your received string.
Correct way to stringify in first place would be:
var innerdata = { name: "neil" };
var eventData = JSON.stringify({ key: "name", data: innerdata });

How Do I See the Output of Changes to JSON

Updated to try to be more clear given the comments (Thank you for comments)
I apologize in advance for this question. I may just not have the vocabulary to properly research it. If I have an array of objects called restaurants stored in my project, for example:
restaurants: [
{
"name": "joes's pizza",
"url": "joespizza.com",
"social properties": {
"Facebook":"fb.com/pizza",
"Instagram":"instagram.com/pizza",
"googlePlus":"pizza+",
"Twitter":"twitter.com/pizza"
}
},
{
"name": "tony's subs",
"url": "tonys.com",
"social properties": {
"Facebook":"fb.com/subs",
"Instagram":"instagram.com/subs",
"googlePlus":"subs+",
"Twitter":"twitter.com/subs"
}
},
{....}
]
I then run a function to add a unique idea to all the objects in the array. The result of console.log(restaurants) is this:
{
"id": 3472,
"name": "joes's pizza",
"url": "joespizza.com",
"social properties": {
"Facebook":"fb.com/pizza",
"Instagram":"instagram.com/pizza",
"googlePlus":"pizza+",
"Twitter":"twitter.com/pizza"
}
},
{
"id": 9987,
"name": "tony's subs",
"url": "tonys.com",
"social properties": {
"Facebook":"fb.com/subs",
"Instagram":"instagram.com/subs",
"googlePlus":"subs+",
"Twitter":"twitter.com/subs"
}
},
{....}
]
I would now like to have this updated array of objects available to look at in my project, via the text editor, as a variable or restaurants.json file. How do I actually see the new modified json array and how do i save it so that i can work with it the same way i did this one above? I am currently doing this in the browser. I can see the results if i log it to the console but I need to be able to work with the new output. Thanks for taking the time to answer.
You can encode/decode JSON with JSON.stringify() and JSON.parse().
Aside from converting to/from JSON, you work with standard JS objects and arrays:
var array = JSON.parse(json_str);
array[0].address = "5th Avenue";
console.log(JSON.stringify(array));
Well, there's really not enough information in your question but I assume a few things:
You've loaded the json data from somewhere and it has been turned into a javascript object.
You've edited the object somehow and wish to convert it back to json and save the changes.
Assuming the above to be true, you just need to serialize the object back to json and submit it back to your server where you can save it in any manner you deem appropriate.
You can serialize the javascript object with JSON.stringify() (see https://stackoverflow.com/a/912247/4424504)
Add the serialized json to a hidden field on the form and submit it.
On the server when processing the form submission, grab the data from the hidden field and do with it what you wish.
Or get it back to the server any way you wish (ajax call, whatever) the key point is to serialize the object to a json string and save it
Hope that helps...

Parsing JSON data from a Website

I have quite a few questions since I'm relatively new at javascript. I started writing this application that lets the user get stock information from the yahoo finance web service and display it on the website. Sounds easy right? I thought so too but I'm having a hard time manipulating the data I'm getting back. Maybe someone can help me get this working. I feel like I'm really close at this point.
The user enters their stock of choice in the stockTextBox such as AAPL or GOOG. Then I set a script attribute with concatenation. Now the confirm() line is VERY odd. If I don't have that confirm in there the alert in the function myCallBack doesn't seem to execute. I can't explain this at all. Maybe I don't now something I should.
Now if I debug I can tell for a back that stock information is coming back from the website. First here is the code and then the JSON data. I would sincerely appreciate it if anyone could help me get this thing to work. I've been fiddling with it for a couple of hours now. THANK YOU! In other words, my question is how do I go about display data that I got from a web service onto my web page?
<form id="stockInput">
Stock Name: <input type="text" id="stockTextBox">
<input type="submit" id="submitButton" value="Submit">
</form>
</b>
<label id="stockLabel"></label>
<script>
var submitButton = document.getElementById("submitButton");
submitButton.addEventListener('click', actionPerformed, false);
function actionPerformed(e)
{
var textValue = document.getElementById("stockTextBox").value;
//tried to put to an element and then read the element value down below through concatenation in the src...
//document.getElementById("stockLabel").innerHTML = textValue;
var script = document.createElement('script');
script.setAttribute('src',"http://finance.yahoo.com/webservice/v1/symbols/"+textValue+"/quote?format=json&callback=myCallBack");
document.body.appendChild(script);
confirm(); //ODD POINT...
}
function myCallBack(data)
{
alert("HEY" + data);
//What I thought I would do. This doesn't output the right info.
//for(key in data)
//{
//alert(data[key]);
//}
}
</script>
</body>
</html>
Now here is the JSON that I can see in the debugger via Firefox:
myCallBack({
"list": {
"meta": {
"type": "resource-list",
"start": 0,
"count": 1
},
"resources": [{
"resource": {
"classname": "Quote",
"fields": {
"name": "Google Inc.",
"price": "1030.579956",
"symbol": "GOOG",
"ts": "1383249600",
"type": "equity",
"utctime": "2013-10-31T20:00:00+0000",
"volume": "1640035"
}
}
}
]
}
});
You are only seeing [object] because it's displaying the data type. You need to get object attributes to obtain the data. The JSON data is very accessible from javascript seeing as how JSON stands for JavaScript Object Notation.
It's very simple once you get started, as the data is basically comprised of objects with attributes and lists of objects. the variable data is your root object, and you can access everything below it easily.
I'll provide a few examples of how you would access certain things in the data:
the attribute "name":
alert(data.list.resources[0].resource.fields.name);
the attribute "classname":
alert(data.list.resources[0].resource.classname);
It's just a text representation of Javascript objects. "resources" is a list of objects, "list" is an object, "fields" is an object, and "price" is a key/value pair to store data.
Read more here: http://www.json.org/
http://www.w3schools.com/json/
If I misunderstood the question let me know, I took a shot at what I thought you meant.
Treat the JSON object like a regular Javascript object. For instance, if you wanted to display the company name and price:
function myCallBack(data)
{
alert("Name: " + data.list.resources[0].resource.fields.name);
alert("Price: " + data.list.resources[0].resource.fields.price);
}
To display the whole thing in raw form for debugging purposes, you can convert it back into a JSON-serialized string:
function myCallBack(data)
{
alert(JSON.stringify(data));
}
More about JSON: https://developer.mozilla.org/en-US/docs/JSON

How to translate Solr JSON response into HTML while JSON is different every time

I am using Solr 4 for searching in a java web application.Solr produces a JSON response from which i have to extract search results and translate them into html so user can read that.
I know one solution but it seems dumb an I think there must be intelligent ideas.
{
"responseHeader": {
"status": 0,
"QTime": 0,
"params": {
"fl": "id,title",
"indent": "true",
"q": "solr",
"wt": "json"
}
},
"response": {
"numFound": 3,
"start": 0,
"docs": [
{
"id": "1",
"title": "Solr cookbook"
},
{
"id": "2",
"title": "Solr results"
},
{
"id": "3",
"title": "Solr perfect search"
}
]
}
}
After that i eval this text as:
var obj = eval ("(" + txt + ")");
To generate html page i can use either
<script>
document.getElementById("id").innerHTML = obj.response.docs[1].id
document.getElementById("title").innerHTML = obj.response.docs[1].title
</script>
or
document.write(obj.response.docs[1].id);
But limitation is that every time solr gives response with different object structure i.e. an object may have age feild but other can not have because it depends on query.
I want to use a sigle JSP page to display search results(like Google)
for all search queries
is it possible to write a single code segment which works for any possible search results with different schema.
Javascript stops working after encountering any error which is likely in my case. that's also problem.if I use for loop to traverse the object hierarchy it is highly error -prone.
Is it possible with a single view page Thanks.
You might want to consider using ajax-solr - A JavaScript framework for creating user interfaces to Solr
I suggest using Velocity templating which is readily supported in Solr - instead of extracting data from the JSON and rendering the HTML via JS.
Docs here

process csv/json data in java servlets and javascript

I need an opinion on how to approach my problem. I have no idea on how to start and on how to implement which functions on which parts of the software. So this is what I want to do:
I have a Java servlet which creates a simple csv file:
name1, value1
name2, value2
etc.
This needs to be somehow converted to JSON data, so it can be displayed on a jsp page:
[
{
"name": "name1",
"value": "value1"
},
{
"name": "name2",
"value": "value2"
}
]
Then the user will be redirected to the jsp page. Is it possible to send the whole JSON structure via request object to the jsp page? Or is it the easiest if all processing is done in javascript and only the path to the csv file is sent via request object?
I'm kind of lost on this, since I first started last week with programming of web applications. I'd just need a push in the right direction and then I should be able to figure out the rest on my own ;)
First, look for a CSV parser which can turn a CSV file into a List<Bean> or List<Map<K,V>>.
Then, look for a JSON parser which can turn a List<Bean> or List<Map<K,V>> into a JSON string.
Finally, just do the math and set the resulting JSON string as a request attribute which you print in JSP as if it's a JS variable, like so <script>var data = ${data};</script>.

Categories

Resources