Convert JSON url to HTML URL - html

http://www.hulu.com/mozart/v1.h2o/shows/54/episodes?show_id=54&sort=seasons_and_release&video_type=episode&_language=en&_region=us&items_per_page=32&position=1&_user_pgid=1&_device_id=1&access_token=sTEbtl-07BZKws2iXobQFRWRzsA%3D8gQbJIixd5b6b896ddf9e57468c8f629c56ca14bcaba6e85ec2664236998c57f6dce5759ae4bbceb1f6442e53302cb02e8ba121f
Need to convert this JSON URL to HTML URL! If we hit the above URL am getting only the JSON script and i want to convert it into HTML table where i can apply xpath to fetch the data.

You have to parse the response by yourself. jQuery can do that: (short example)
var doc = $('#table');
$.getJSON('url', function (res) {
$.each(res, function (x) {
doc.append('<tr>');
doc.append('<td>'+x.description+'</td>');
doc.append('</tr>');
});
});

Related

Read a external json file in Neutralino app

How can I read a external json file to populate my HTML?
I read the docs and see "filesystem.readFile(string filename, function success(data), function error)" but I don't know how can I set to read the file or what is the right folder to put the file.
This code from the docs prints the data from the json file. Consider parsing the returned json. NOTE : the function should always be an "async" function or it won't work.
async function readMyjsonFile(){
let response = await Neutralino.filesystem.readFile({
fileName: './myFile.json'
});
console.log(`Content: ${response.data}`);
}
If you use jQuery you can use jQuery.getJSON() (https://api.jquery.com/jquery.getjson/).
jQuery.getJSON('relativePath/myFile.json',function(data){
//Do something with your json data
}
or
jQuery.getJSON('file:///absolutePath/myFile.json',function(data){
//Do something with your json data
}

Parse JSON returned from NODE.js

I’m using jQuery to make an AJAX call to Node.js to get some JSON. The JSON is actually “built” in a Python child_process called by Node. I see that the JSON is being passed back to the browser, but I can’t seem to parse it—-although I can parse JSONP from YQL queries.
The web page making the call is on the same server as Node, so I don’t believe I need JSONP in this case.
Here is the code:
index.html (snippet)
function getData() {
$.ajax({
url: 'http://127.0.0.1:3000',
dataType: 'json',
success: function(data) {
$("#results").html(data);
alert(data.engineURL); // alerts: undefined
}
});
}
server.js
function run(callBack) {
var spawn = require('child_process').spawn,
child = spawn('python',['test.py']);
var resp = '';
child.stdout.on('data', function(data) {
resp = data.toString();
});
child.on('close', function() {
callBack(resp);
});
}
http.createServer(function(request, response) {
run(function(data) {
response.writeHead(200, {
'Content-Type':
'application/json',
'Access-Control-Allow-Origin' : '*' });
response.write(JSON.stringify(data));
response.end();
});
}).listen(PORT, HOST);
test.py
import json
print json.dumps({'engineName' : 'Google', 'engineURL' : 'http://www.google.com'})
After the AJAX call comes back, I execute the following:
$("#results").html(data);
and it prints the following on the web page:
{“engineURL": "http://www.google.com", "engineName": "Google"}
However, when I try and parse the JSON as follows:
alert(data.engineURL);
I get undefined. I’m almost thinking that I’m not actually passing a JSON Object back, but I’m not sure.
Could anyone advise if I’m doing something wrong building the JSON in Python, passing the JSON back from Node, or simply not parsing the JSON correctly on the web page?
Thanks.
I’m almost thinking that I’m not actually passing a JSON Object back, but I’m not sure.
Yes, the ajax response is a string. To get an object, you have to parse that JSON string into an object. There are two ways to do that:
data = $.parseJSON(data);
Or, the recommended approach, specify dataType: 'json' in your $.ajax call. This way jQuery will implicitly call $.parseJSON on the response before passing it to the callback. Also, if you're using $.get, you can replace it with $.getJSON.
Also:
child.stdout.on('data', function(data) {
resp = data.toString();
// ^ should be +=
});
The data event's callback receives chunks of data, you should concatenate it with what you've already received. You probably haven't had problems with that yet because your JSON is small and comes in a single chunk most of the time, but do not rely on it, do the proper concatenation to be sure that your data contains all the chunks and not just the last one.

GDocs Script to fetch web info behind a form using UrlFetchApp

I want to fetch some web data using GDocs but the data is behind a form so I need to post some data to the form to get the result. (So I cant use ImportXML etc)
The function that I am trying to use is https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app but I dont really know where to start since I don't have much java script experience.
Is there anyone that has a script that takes an url, form name & the data to post that can be used in GDocs?
There's an example of such a script here: How do I use Google Apps Script to change a CSS page to one with inline styles?.
It's a different application, but the method applies. Here's a skeleton function to get you started.
The payload object should contain the name / value pairs of the form data you want to simulate. The url should be changed to match the site you're submitting the form to. Once you've made the POST request by the call to UrlFetchApp.fetch(), you should be able to parse the response using the getElementByVal() utility from Does Google Apps Script have something like getElementById?.
function postForm() {
// Generate a POST request with form data.
var payload =
{
"name" : 'Anonymous Person', // Replace with relevant name / value pairs
"town" : "Springfield"
};
// Because payload is a JavaScript object, it will be interpreted as
// an HTML form. (We do not need to specify contentType; it will
// automatically default to either 'application/x-www-form-urlencoded'
// or 'multipart/form-data')
var options =
{
"method" : "post",
"payload" : payload,
"muteHttpExceptions" : true
};
var url = "http://form.somewhere.com"; // Replace as appropriate
var response = UrlFetchApp.fetch(url, options);
// Put the receieved xml response into XMLdocument format
var xml = response.getContentText();
var doc = XmlService.parse(xml);
// Extract the details you want...
var someData = getElementByVal( doc, 'textarea', 'name', 'text' );
...
}

calling JSON webservice & using html

I've been using XML a lot lately but now I'm practicing with some JSON.
What I am trying to do is make a button and text box - so the user can type in a zip code and it will get the info for that zip code...
Using JSON from geonames.org
It's frustrating me trying to figure this out, I've found it easy when I was making my own files with XML but now I am trying to use an actual website and JSON.
Please show me how to do this! Would appreciate it! Thanks.
First of all HTML cannot process a json response from a server. You can send a get or post in json format to a server and get a json response back but you need something other than HTML to process that JSON message. Browsers can format and display XML but not JSON (they just display it as a string). The easiest way to do that in a browser is use JavaScript. For this I would recommend using the jquery library.
http://jquery.com
Here's an example of some jquery I used recently to process a returned JSON string.
$(document).ready(function() {
$(".img a").on("click", function(event) {
event.preventDefault();
var item;
if ((item= $(this).attr( 'href' ))=="saved") return false;
$(this).html("<div style='line-height:4em '>Saved</div>");
$(this).attr("href","saved");
var action ="add";
jqxhr = $.post("webservice.php", { action: action, color: item }, function(data) {
var result=data.result;
if (result=="saved") {
self.html("<div>Saved</div>");
self.attr("href","saved");
}
}, "json")
.error(function() {
alert("error: unable to contact web service");
});
});
});
The returned JSON string from this request is { result: saved }. So as you can see you access the associated array as part of the data object. In my case data.result provided me with the value of result from the json string.
Note my example is for using an anchor tag to pass a value to send in the webservice call. In your case you will need to use a form.
If you're using jeoquery then just look at the html source of UI sample. It's showing the same autocomplete box that you might be trying to implement no custom code to write to parse returned JSON. Below code should work for you:
<input class="input-large" id="city" type="text"/>
$("#city").jeoCityAutoComplete();

How to parse ASP.NET JSON Date format with GWT

ASP.NET JSON serialize DateTime to the following format "/Date(1251877601000)/". Pls, help parse this string into the java(GWT) Date object.
At this time the solution I came with is parsing with regex, extract long.. but then I cannot push long through JSNI.
function FixJsonDates(data) {
//microsoft script service perform the following to fix the dates.
//json date:\/Date(1317307437667-0400)\/"
//javasccript format required: new Date(1317307437667-0400)
//copied from micrsoft generated fiel.
var _dateRegEx = new RegExp('(^|[^\\\\])\\"\\\\/Date\\((-?[0-9]+)(?:[a-zA-Z]|(?:\\+|-)[0-9]{4})?\\)\\\\/\\"', 'g');
var exp = data.replace(_dateRegEx, "$1new Date($2)");
return eval(exp);
}
The answer to this question is, use nuget to obtain JSON.NET then use this inside your JsonResult method:
return Json(JsonConvert.SerializeObject(/* JSON OBJECT TO SEND TO VIEW */));
inside your view simple do this in javascript:
JSON.parse(#Html.Raw(Model.data))
If it comes via a view model that is or if it is an ajax call:
var request = $.ajax({ url: "#Url.Action("SomeAjaxAction", "SomeController")", dataType: "json"});
request.done(function (data, result) { JSON.parse(data); });