New to JSON, just trying to get my feet wet.
I know how to do this with XML via javascript, but am trying to learn how to handle JSON objects so I can switch over.
Basically I want to search through all "permalink" tags in the following JSON object and, when I find the right one, save its corresponding "title" and "id" tags to javascript variables:
http://api.soundcloud.com/users/goldenstatewarriors/tracks.json?client_id=02db8e29aa2fb5bf590f478b73137c67
Can this be done with only javascript (no PHP)? The main issue I'm facing is simply grabbing the text from the page and converting it to a json object.
You need to use a JSON parser in order to transform the JSON string into an object you can handle natively in JavaScript. Recent browsers have this functionality built in as JSON.parse(), but obviously this will not work in older browsers (we're talking very old browsers here).
A solution to that problem is to use the JSON parsing library available here. If native browser support is detected, it simply uses that, otherwise it has a JavaScript implementation to achieve the same result. The file you'll need is json2.js - simply include that as you would any other library and away you go!
An example of the code would be:
var dataObject = JSON.parse(jsonData);
As a side note, XMLHttpRequest is somewhat of a misnomer these days. It is simply a mechanism for making HTTP requests and retrieving the data returned, it doesn't have to be XML. It can be plain text, (non X)HTML, JSON, anything. In fact, I don't think I've seen anything in the wild return actual XML data for an XMLHttpRequest in a very long time.
Related
I've read a lot about sanitizing and escaping of untrusted data, e.g. starting with this cheat sheet. But I didnt get the full picture yet. I am struggeling to understand, what principles I have to follow in order to parse JSON data safely.
Let's be more precise by means of an example. I retreive an Object in JSON format via an Ajax call from my server. The object shoudnt contain any malicious code, but.... you never now. So I parse the JSON data using JSON.parse in JS. The sesult is a multilevel JS object. I use the object in various way, e.g. creating table code via JS and writing it in the DOM.
Is this approach safe. Or do I have to somehow escape the invidual items of the object individually? Appreciate your help. Happy to concrete my example if necessary.
If there is a cookie on our website called cabbages and $.cookie("cabbages") returns this:
"purchaseType":"NONE","futurePurchaseType":"NONE","id":73041988,"unlimitedStatus":null,"hasFuturePrivilege":false,"corpUser":false,"suspendedStatus":null,
What is the prescribed or conventional way to get back the value of id? I want the ID of the visitor so in this example I'd like to write some Javascript that returns 73041988.
Contents of your cabbages cookie looks very close to json object syntax to me. So JSON.parse() would be naturally the way I would take. You just need to add curly braces to that string to make it valid json object syntax.
Actually this has got nothing to do with cookies. If any variable contains data having syntax similar to this, you can always go for JSON.parse() to extract it in to a javascript variable.
Json objects look like:
{name1:value1,name2:value2,name3:value3}
Similarly a json array looks like:
[value1,value2,value3]
and you could use JSON.parse for any data having json sytax.
You can see some more good examples of JSON syntax in links below.
http://json.org/example
http://www.tutorialspoint.com/json/json_syntax.htm
Please note that this JSON API which provides native support for json serialization in javascript may not be available in some older browsers and the function call will fail.
As you mentioned $.cookie() in your question, I guess that your project is already using JQuery. So you better use jQuery.parseJSON(), which makes use of JSON.parse where the browser provides a native implementation, and also provides a fall back parser when browser support is not available.
This Stack Overflow thread has more details about Native JSON support in browsers.
Here's the two scenarios.
We are using a manually built xml soap request with xmlhttprequest, sending it to a wcf soap service, getting back the response and using xPath to parse the data and fill out a drop down list.
We are sending a json request to a rest wcf service and getting a json response back and assigning the values to a drop down list
Which scenario is faster? My sense tells me #2 but I could be wrong.
Json will be faster, since Json is essentially Javascript. But that shouldn't be the main motivation. Parsing the data, will assumingly be only a small part of your application anyway.
On the other hand, browsers are also well trained to parse XML.
The main difference is that XML, and therefor SOAP, is larger to send to the client, so the transfer may be a bigger slowdown than the parsing.
Anyway, if you want to know, you should just test and profile instead of guessing or asking.
Option two would generally be faster than option one, as JSON is a much simpler format than XML.
However, if you really need the parsing to be fast, you shouldn't use either, you should use a custom format that is really fast to parse using simple string operations. For example a comma separated string that could be parsed with a split(',').
After profiling in my scenario, I found out that JSON is actually much faster as far as processing time within the browser
i'm trying to send three arrays of data from one .js file which is used by first webpage to the other .js file which is used by the second webpage.
the data in the first webpage is dynamically built so those three arrays are to be sent to the next webpage.
can anyone suggest some javascript code or tutorial.
please help...............
Thank you Guys. . . . ..
I'd suggest using the JSON data format. JSON is like XML except a lot easier to parse through. Some great examples can be found on Jquery's page:
http://api.jquery.com/jQuery.getJSON/
Everything you need to read the JSON feed can be found on jQuery. If you need to know how to structure a JSON feed you can read about it here:
http://www.json.org/js.html
This is really tough to do with strictly javascript and html. Here are some options:
You could store the array in a hidden form variable and post it to the destination page
If the dataset is small enough (< 4K), then you can store it in a cookie across requests.
If you are only using the most modern browsers (read: HTML5), you can use localstorage
You could encode the data and pass it in the url
In general, though, these are mostly hacks. Usually this kind of work is augmented by some type of server-side processing (perl, php, asp.net, etc) in which you have available some kind of storage across requests (i.e. Session in asp.net).
You could use the Web Storage API, and include a polyfill to port the functionality for older browsers:
http://code.google.com/p/sessionstorage/
https://gist.github.com/350433
Both of these use window.name to provide a session-like state. This may or may not be secure enough for your needs.
From there, you can use the following code for all browsers:
// Store on previous page
sessionStorage.setItem("yourArray", JSON.stringify(yourArray));
// Restore on following page
var yourArray = JSON.parse(sessionStorage.getItem("yourArray"));
EDIT: Older browsers may need the following for the above code sample. This is so the array can be serialized to a string, since sessionStorage only supports string key-value pairs:
https://github.com/douglascrockford/JSON-js
Check out jQuery.data() and friends. Cf.: http://api.jquery.com/category/data/
You may use cookie for that purpose.
I'm building an AJAJ (AJAX with JSON) webapp with jQuery and I'd like my users to be able to bookmark a page that saves all of their setting selections for a certain part of the app. I've got quite a bit of data that needs to be saved, so I thought JSON might be the best way to save this, putting it into the location.hash.
That being said, what's the best way to get the string of data from the location.hash and convert it back to a JSON object so that it's usable inside the Javascript?
Here's what I'm thinking as far as the JSON object
http://example.com/index.html#json={'s': '2010-02-19', 'array':[1,2,3,4]}
Roland suggested that I drop the json=, successfuly cutting 5 characters out, too. So the complete location would be:
http://example.com/index.html#{'s': '2010-02-19', 'array':[1,2,3,4]}
Example assuming you have JSON support (either native or by including a JSON parse script)
var obj, text = document.location.hash;
if (text){
obj = JSON.parse(text);
}
If the browser does not have native JSON support, you can grab a script from http://www.json.org/js.html or use some framework supported variant (like YUI's http://developer.yahoo.com/yui/json/)
You say 'quite a bit'. Can you be more specific? Bear in mind that you are limited to 2083 characters on your URL.
Personally, I would be reticent to store this sort of stuff in the command line anyway. You'll have pain dealing with URL encoding/decoding, and people can get an Idea of your data structures, and possibly hack the JSON string in the URL.
Have a look at the history plugin, it might be relevant to your needs