admin管理员组文章数量:1331619
I have a URL that returns an
application/json
Content-Type
. When I browse to that URL, I'd get a plain-text JSON array in my browser window
[[key, value],
[key, value],
[key, value],
...]
I also have a JavaScript function that expects data to be in JSON array format
function process_data() {
var data = // give me more data in JSON array format...
}
How do I make my JavaScript browse to and assign the resulting JSON array into the
data
variable inside process_data()
?
I'm new to JavaScript (ing from a Python background) and I would appreciate if you can suggest solutions that use the core JavaScript library. Solutions using other libraries are wele also, preferably those that are considered best-practice.
UPDATE
It appears I wasn't clear on my question. Let me provide an example from Python. After doing the necessary imports, I can do something like
url = ""
page = urllib2.urlopen(url)
page_source = page.read()
This time, page_source
is already a Python str
object that I can easily play with, assign to other variables, etc. If I could mix Python and JavaScript together, for the context of this question, I want to do something like
function process_data() {
url = ""
page = urllib2.urlopen(url)
page_source = page.read()
var data = convert_str_to_JSON(page_source)
}
Of course that was just an ugly mishmash of a code, but I hope it conveys what I'm trying to get at:
- JavaScript will
GET
a URL. - Read the source.
- Interpret source as JSON.
- Assign it to a variable.
I have a URL http://myapp./get_data
that returns an application/json
Content-Type
. When I browse to that URL, I'd get a plain-text JSON array in my browser window
[[key, value],
[key, value],
[key, value],
...]
I also have a JavaScript function that expects data to be in JSON array format
function process_data() {
var data = // give me more data in JSON array format...
}
How do I make my JavaScript browse to http://myapp./get_data
and assign the resulting JSON array into the data
variable inside process_data()
?
I'm new to JavaScript (ing from a Python background) and I would appreciate if you can suggest solutions that use the core JavaScript library. Solutions using other libraries are wele also, preferably those that are considered best-practice.
UPDATE
It appears I wasn't clear on my question. Let me provide an example from Python. After doing the necessary imports, I can do something like
url = "http://myapp./get_data"
page = urllib2.urlopen(url)
page_source = page.read()
This time, page_source
is already a Python str
object that I can easily play with, assign to other variables, etc. If I could mix Python and JavaScript together, for the context of this question, I want to do something like
function process_data() {
url = "http://myapp./get_data"
page = urllib2.urlopen(url)
page_source = page.read()
var data = convert_str_to_JSON(page_source)
}
Of course that was just an ugly mishmash of a code, but I hope it conveys what I'm trying to get at:
- JavaScript will
GET
a URL. - Read the source.
- Interpret source as JSON.
- Assign it to a variable.
- first of all the json you show in your example is not json. its an array of arrays. – codeandcloud Commented Aug 14, 2011 at 6:39
- copy [[key, value], [key, value], [key, value], ...] to jsonlint. and check validity. please paste your actual response. – codeandcloud Commented Aug 14, 2011 at 6:45
-
1
@naveen. Yes, my example per se is invalid JSON.
key
andvalue
are meant to be placeholders. JSONLint didn't say anything about array of arrays being an error. It only plained about expected data types.[["key", "value"], ["key", "value"]]
are good enough. – Kit Commented Aug 14, 2011 at 6:50 - i stand corrected. i have always thought they would be wrappoed to a parent object – codeandcloud Commented Aug 14, 2011 at 7:02
4 Answers
Reset to default 7Newer browser support JSON parsing natively.
You can say JSON.parse('json data')
. For older browsers (such as IE 7 or 6), you can use this library: https://github./douglascrockford/JSON-js
Use json2.js
from above library. It checks if native browser implementation is present, if not, adds it.
Do not use eval
(as eval is evil)!
Update: To get the 'json data', use this:
var jsonObject = {};
var xhr = new XMLHttpRequest();
xhr.open( "GET", url, true ); // true makes this call asynchronous
xhr.onreadystatechange = function () { // need eventhandler since our call is async
if ( xhr.readyState == 4 && xhr.status == 200 ) { // check for success
jsonObject = JSON.parse( xhr.responseText );
}
};
xhr.send(null);
Also, I would suggest reading this article for cross browser issues and implementation of XMLHttpRequest
object.
Using JQuery is almost a standard nowadays:
$.get('/get_data', function (data) {
//success callback
}, 'json');
I did a fiddle here, look the sample here: http://jsfiddle/b24GZ/ - Fetching json data from: http://api.geonames/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo
References:
http://api.jquery./jQuery.get/
http://api.jquery./jQuery.post/
http://api.jquery./jQuery.parseJSON/
There's a couple ways. If you're using a library of some kind, most of them have built-in JSON.parse() methods. Newer browsers (i.e. Chrome, Firefox, Safari, etc) have that capability built in.
Another way of doing it is with a jsonp callback. With this method, you define a function on your in your script and then write a script tag into the page loading the url you wish to load as its source. You pass the name of your function as a parameter to your remote uri, and your server wraps the json response with the callback. When it loads onto into the page, your function executes using the data it wraps as a javascript object.
This is a simple example:
var your_callback = function(obj){
console.log(obj);
}
<script src="http://myapp./get_data/?callback=your_callback"></script>
At this point, your_callback gets executed and the "obj" variable contains your data.
Again, if you have the advantage of using a javascript library, this functionality might already be baked in. jQuery makes this bit really easy.
JSONP is typically used for cross-domain data transfer, but it works just as well locally. If you are doing this locally though, you shouldn't need to use JSONP and can use XHR requests instead.
If you use jQuery library, it's possible to use jquery-jsonp library code.google. jquery-jsonp
function getProfile(userId) {
$.jsonp({
"url": "http://gdata.youtube./feeds/api/users/"+userId+"?callback=?",
"data": {
"alt": "json-in-script"
},
"success": function(userProfile) {
// userProfile - is JSON data with which you can work
// handle user profile here
},
"error": function(d,msg) {
alert("Could not find user "+userId);
}
}); }
Also in your "http://myapp./get_data" page youw will need to put JSON data into callback data
callback(json_data_here)
本文标签: Retrieve plain text JSONinsert into JavaScriptStack Overflow
版权声明:本文标题:Retrieve plain text JSON, insert into JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742260026a2442341.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论