Get JSON page content with PhantomJS - json

I would like to know how to parse JSON in phantomjs. Any page content is enclosed in html (<html><body><pre>{JSON string}</pre></body></html>). Is there an options to remove enclosing tags or asking for a different Content-Type as "application/json"? If not, what's the best way to parse it. Is it using jQuery after including with includeJS jQuery?

Since you are using PhantomJS which is built of the webkit browser you have access to the native JSON library. There is no need to use page.evaluate, you can just use the plainText property on the page object.
http://phantomjs.org/api/webpage/property/plain-text.html
var page = require('webpage').create();
page.open('http://somejsonpage.com', function () {
var jsonSource = page.plainText;
var resultObject = JSON.parse(jsonSource);
phantom.exit();
});

Here is what I did:
var obj = page.evaluate(function() {
return eval('(' + document.body.innerText + ')');
}
Then the obj you got is the JSON object returned from that page.

As already in the accepted answer, I would suggest using JSON.parse() for converting a JSON string into an object.
For example, your code could look like this:
var jsonObject = page.evaluate(function() {
return JSON.parse(page.plainText);
});

If the json data contains html strings, they will be removed within the suggested page.plainText attribute.

Related

How to correctly parse html response in Postman

I'm getting the response in html. All tutorials are using:
var y = document.getElementsByClassName('mw-search-result-heading');
or
var jsonData = JSON.parse(response);
and they both fail.
First one due to document not defined, second because response is not JSON but HTML.
So, how can I correctly parse an html in Postman ?
Hi you can use cheerio jQuery api
Example:
const $ = cheerio.load(pm.response.text();
console.log($("title").text()); // get title

parse model data to JSON object

I need to convert a list of model objects into a JSON list.
<a data-model="#Model.Schools"></a>");
The list of schools is parsed to a jquery eventhandler when the above button is pressed (I left some code out here)
Here, I naturally want to read the list of schools to a json list.
var items = JSON.stringify(button.data('model'))
var items2 = JSON.parse('"' + button.data('model') + '"')
I tried the above, however without any luck, it still yells at me for trying to convert a System.Collections.Generic.List`1.
Also I tried to serialize the object to JSON at the button, i.e. #HTML.raw(Json.Serialize(Model.Schools) but it just gives me an empty object in my jQuery...
Therefore, how do I convert a Model object to a json object in jQuery?
If I get your problem statement correctly, it seems you are pretty much there.
you need to serialise your list into Razor attribute (don't use #Html.Raw helper as it will not escape your string and mess with your page):
Full .net framework
<a id="btnModel" data-model="#Json.Encode(Model.Schools)" onclick="process()">TEST</a>
<!-- assuming you have Newtonsoft.Json package installed, the following line should also work-->
<a id="btnModel" data-model="#Newtonsoft.Json.JsonConvert.SerializeObject(Model.Schools)" onclick="process()">TEST</a>
and then in your Javascript:
function process() {
var m = $('#btnModel').data('model');
alert(JSON.stringify(m));
}
check out this dotnet fiddle for working example
.net core 3
Apparently the built-in serilizer somehow garbles the formatting so it needs proper html encoding. This unfortunately will mean you have to decode it in Javascript. One way to avoid this hassle would be to output your json string into javasctipt block (see second example)
<a id="btnModel" data-model="#Html.Encode(Json.Serialize(Model.Schools))" onclick="process()">Method 1 - Lotsa pain</a>
<a id="btnModel1" onclick="process1()">Method 2 - Less back and forth</a>
function decodeHtml(html) {
var txt = document.createElement("textarea");
txt.innerHTML = html;
return txt.value;
}
function process() {
var a = $('#btnModel').data('model');
a = JSON.parse(decodeHtml(a));
alert(JSON.stringify(a));
}
function process1() {
var a = #Json.Serialize(Model.Schools);
alert(JSON.stringify(a));
}

Javascript does not accept HTML String from MVC?

Javascript does not accept HTML String from MVC?
My MVC contoller from where I am sending the HTML template in string from txt file
using (StreamReader sr = new StreamReader(#"D:\Templates\NewGridTemplate.txt"))
{
// Read the stream to a string, and write the string to the console.
obj.sGridTemplate = sr.ReadToEnd().Replace(Environment.NewLine, " ");
//Console.WriteLine(line);
}
return View(obj);
Actual code in csHTMl Javascript
var sHTML=$(#Model.sGridTemplate);
Below is screen shot for error . HTML string is not accepted by Javascript. shows character "<" etc.. Please help let me know what I missed.Image 3
You need to put your content within quotes so that it becomes a Javascript string, otherwise it'll be interpreted as syntax and you get the error because it's not valid JS syntax
var sHTML=$('#Model.sGridTemplate');
And the problematic line in the resulting client-side code should look more like this:
var sHTML=$(' < ...
... than:
var sHTML=$( < ...

cordova readAsText returns json string that can't be parsed to JSON object

I read my json file using http and cordova file readAsText functions.
http request returns an object which is ok.
cordova file readAsText function return 'string' which contain extra "r\n\" symbols. This make it impossible to use JSON.parse(evt.target.result)
function readJson(absPath, success, failed){
window.resolveLocalFileSystemURL(absPath, function (entry) {
entry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function (evt) {
success(evt.target.result);
};
reader.readAsText(file);
}, failed);
}, failed);
}
readJson(cordova.file.dataDirectory + 'my.json', function(res){
console.log(JSON.parse(res)); //here I've got an parsing error due to presence of r\n\ symbols
}, failed );
How to read JSON files using cordova?
UPDATE:
funny thing that the following works:
a = '{\r\n"a":"1",\r\n"b":"2"\r\n}';
b = JSON.parse(a);
so the problem not only with \r\n... there is something else that is added by cordova readAsText
UPDATE2
as a workaround I use now var object = eval("(" + res + ")")
Still search for a common way to load json objects...
No one has answered this and I just had to solve it for my project, so I will post my solution.
The readAsText method outputs a string, so you CAN actually run a replace on it, but what you need to do is use a RegExp to find the newline character. here's my solution:
var sanitizerRegex = new RegExp(String.fromCharCode(10), 'g');
var sanitizedData = JSON.parse(result.replace(sanitizerRegex, ''));
I've used the String method fromCharCode to get the specific newline character and the "g" flag to match all instances in the entire string. The problem with your string solution is that you can't do a string replace using the characters for backslash and "n" because the issue is the actual new line character, which is merely represented as "\n".
I do not know the reason JSON.parse can't handle the newline character, or why the file plugin introduces this problem, but this solution seems to work for me.
Also, NEVER use eval like this if you can avoid it, especially on input from a source like a JSON file. Even in a cordova app, using eval is potentially very unsafe.
I found out the solution after debug deeply. readAsText function returned text has one more letter at the first position of text.
Example:
{"name":"John"} => ?{"name":"John"} (?: API didn't return ?, just one string)
I confirmed this with length of result, so we need to use substr(1) before parse JSON.
fileContent = fileContent.substr(1);
var jData = jQuery.parseJSON(fileContent);

How to get the values from the Json using Jquery

Hi I'm new to Jquery and i don't know how to use json data. I have a Json which is coming as a response. My success function is
success: function(resp)
{
var x = JSON.stringify(resp);
alert(x);
}
alert is having following JSON
{"xyz":{"abc":[{"action":"fail","result":"xxx"},{"action":"pass","resut":"yyy"}]}}
I want action value alone. How can i get this value from x variable and how can i utilize this value in HTML. Thanks in advance.
When you use JSON.stringify() you are turning it into a string, you want it as an object to access the data. Try this:
success: function(resp) {
alert(resp.xyz.abc[0].action);
var x = resp.xyz.abc[0].action // to use the value in html later on
}
If it is returned as a string (I can't tell at this point), you can turn it into an object (as long as it is valid JSON) by using $.parseJSON()
success: function(resp)
{
var x = $.parseJSON(resp);
var xyz = x.xyz;
var pass = x.xyz.abc[1].action;
}
or you can loop though each of the array by $.each
success: function(resp)
{
var x = $.parseJSON(resp);
$.each(x.xyz.abc, function(index, element){
alert('action:' + element.action + ', result:' + element.resut)
});
}
i think, and don't take it personally,that your JSON object is not well organized as an object to get and to have. Action,from my perspective is either fail or success, and reading it, as you saw in the above good answer, will give you exactly what you want.
What's the point in getting a JSON with data structured like you did, with 2 possible answers encoded in it, when there is only one available (either success or fail).