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
Related
Goodday fellow programmer,
I'm having trouble adding an object to my JSON file. I'm using jQuery.
My javascript file:
$('#addchallenge').click(function()
{
//hardcoded challenge
var addchallenge =
{
"achievementname": "I am an achievement who want to be added to the list",
"points": "50",
"comment": "guess who has been a nasty achievement to add"
}
$.getJSON("../json/package.json", function (data)
{
$.each(data.allachievements, function ()
{
//very suspicious line here:
this["achievementlist"].push(addchallenge);
});
});
});
My external JSON file:
{
"allachievements":[
{
"name": "list of all achievements",
"achievementlist": [
{
"achievementname": "first achievement",
"points": "30",
"comment": "the first achievement to achieve"
},
{
"achievementname": "second achievement",
"points": "-90",
"comment": "is worth a negative amout of points"
},
{
"achievementname": "aaand the 3th achievement",
"points": "30",
"comment": "do you already have achievement 1 and 2?"
}]
}]
}
How could the addchallenge data be added into my JSON file?
Do I need to parse my JSON data, add my challenge to add, then stringify it back?
Thanks in advance :)
You cant directly manipulate the JSON file - Writing, deleting etc.
However, you could write some backend code thats capable of this.
If you simply want to temporally add an achievement, you can parse in your JSON file into a variable and then manipulate it.
You can't modify the JSON file only with client side code. You need some server side code.
I would recommend you to use post().
EDIT:
I actually found this: How to : edit an external json file in javascript
So, current post may be considered a duplicate...
Are you trying to write into a file using jquery?
if so please check the following url:
Read/write to file using jQuery
Your problem is this, the context. Inside of the callback you are passing to $.each iterator, this is not what you think it is.
jQuery.each( array, callback )
callback
Type: Function( String propertyName, Object valueOfProperty )
The function that will be executed on every object.
I would change your code like this:
$.getJSON("../json/package.json", function (data)
{
$.each(data.allachievements, function (key, value)
{
value["achievementlist"] = value["achievementlist"] || [];
value["achievementlist"].push(addchallenge);
});
});
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...
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
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
I have a local url where i can retrieve a json file. I also have a simple website which is build using JQuery.
I've looked up many sites for tutorials and sample code on how to retrieve the json input and parse it so i can display it on my site. However non were helpful as i still can't make it work.
So as a last resort i'm going to ask stackoverflow for your help. I have a lot of java knowledge, but I'm relative new to 'web'-development and know some basics of javascript.
This is a sample output of my url:
[
{
"baken": "not implemented...",
"deviceType": "Optimus 2X",
"batteryLevel": "1.0",
"gps": {
"speed": 0,
"Date": "TueNov0100: 34: 49CET2011",
"Accuracy": 35,
"longitude": {removed},
"latitude": {removed},
"Provider": "gps"
},
"deviceId": "4423"
},
{
"baken": "notimplemented...",
"deviceType": "iPhone",
"batteryLevel": "30.0",
"gps": {
"speed": 0,
"Date": "TueNov0116: 18: 51CET2011",
"Accuracy": 65,
"longitude": {removed},
"latitude": {removed},
"Provider": null
},
"deviceId": "4426"
}
]
Hope you can help me..
If you are running a local web-server and the website and the json file are served by it you can simply do:
$.getJSON('path/to/json/file.json', function(data) {
document.write(data);
})
If you are just using files and no webserver you might get a problem with the origin-policy of the browser since AJAX request cannot be send via cross-domain and the origin domain is 'null' per default for request from local files.
If you are using Chrome you can try the --allow-file-access-from-files parameter for developing purposes.
Your URL returns invalid json. Try pasting it in jsonlint.com and validating it there and you'll see what I mean. Even the code highlighting here on stackoverflow is showing you what's wrong. :)
Edit: To parse it you can use jQuery.parseJSON
jQuery.parseJSON('{"foo": "goo"}');
$.get('/some.json', function(data) {
// data[0]["baken"] == "not implemented..."
});
See http://api.jquery.com/jQuery.get/
You don't need to parse the json -- that is why people like it. It becomes a native JavaScript object.
For your example if you put the results in a variable called data then you could do things like this:
data[0].deviceType // would be "Optimus 2x"
data[0].gps.speed // would be numeric 0
etc.
The most natural way is to allow jQuery to make an AJAX call for you once you've already entered the page. Here's an example:
$.ready(function() {
// put your other code for page initialization here
// set up a global object, for namespacing issues, to hold your JSON.
// this allows your to be a good "web" citizen, because you will create
// one object in the global space that will house your objects without
// clobbering other global objects from other scripts, e.g., jQuery
// makes the global objects '$' and 'jQuery'
myObjects = {};
// start JSON retrieval here
$.getJSON('/path/to/json/file.json', function(data) {
// 'data' contains your JSON.
// do things with it here in the context of this function.
// then add it to your global object for later use.
myObjects.myJson = data;
});
});
The API documentation is here