xPages - set javascript variable by reading JSON from URL - javascript

I have an xAgent (based on JSONandRest example in openntf by Nikolas Heildoff) which returns me a json. this xpage is nothing by there is a call to java method which returns JSON.
My problem is to have this JSON read into a JS variable so I am able to play with it.
I would like to do something like:
var myJson = getJson("Json.xsp")
Thanks in advance
Arun

You can use the fromJson method:
var json = "{a:'123', b: 'abc'}";
var obj = fromJson( json );
println( obj.a );
This sends 123 to the console.

Related

Json obj is not acting correct way in javascript

I am trying to get form data to json object and modify it... But it is not working...
Here is my code-
let formData = new FormData(thisForm).entries();
let body = JSON.stringify(Object.fromEntries(formData));
console.log(body);
console.log(body.firstName);
console.log("service=" + body.service);
body.service = "hello";
the console.log(body) is printing output like this-
{"prospectType":"1","firstName":"Arnab","middleName":"","lastName":"Maiti","mobileNumber":"07xxxxxx","workPhoneNumber":"","sourceOther":"","streetArea":"Kanakpur","service":"OTT"}
But console.log(body.firstName); is printing undefined.
Same thing is happening for other things.. What is the problem?
It's because body is a string, not a JSON object, because you've JSON.stringify'd it.
Use JSON.parse instead to create a JSON object that you can edit like that.
var body = '{"prospectType":"1","firstName":"Arnab","middleName":"","lastName":"Maiti","mobileNumber":"07xxxxxx","workPhoneNumber":"","sourceOther":"","streetArea":"Kanakpur","service":"OTT"}';
var jsonBody = JSON.parse(body);
console.log(jsonBody.firstName);
Because you use JSON.stringify() on the object first.
You use that to transfer the object over http. Apply that later on and you're fine.

My code wont print my object

When I try to print my object it gives me no response.
var steaminv = JSON.parse("http://steamcommunity.com/id/pootel/inventory/json/730/2.json");
document.write(steaminv);
You should request the file first and then parse the content of the file.
JSON.parse requires a json object encoded as string. It does not request the file for you.
If you are using node, you can use request module. If you are using javascript on browser, you can use jQuery and do an ajax call to get the content of the file.
Please take a look at this question: How do I receive a JSON file using AJAX and parse it using javascript?
Just to give you an idea what JSON.parse does:
var str = '{"name":"Amir","age":25}';
var obj = JSON.parse(str);
console.log(obj.name);
console.log(obj.age);

Getting an error on JSON.parse

I was reading an article by Derick Bailey Don’t Return A JSON Document From The toJSON Method
I was trying to convert the following JSON object into Javascript:
var userJSON = "{\"firstName\":\"Derick\",\"lastName\":\"Bailey\"}";
var parseOnce = JSON.parse(userJSON.to_json).first;
var userObject = JSON.parse(parseOnce.to_json).first;
When I run the code I get a "SyntaxError: Unexpected token u"
Here is a jsbin of the same code https://jsbin.com/zugojoyaro/edit?js,console
this is a copy & paste problem from the blog post... (and a small error in the blog post, itself)
var userJSON = "{\"firstName\":\"Derick\",\"lastName\":\"Bailey\"}";
var parseOnce = JSON.parse(userJSON);
this works... but the code you have:
var parseOnce = JSON.parse(userJSON.to_json).first;
includes a .to_json and a .first attribute that don't exist. it looks like your trying to use ruby code on a JavaScript object

Print data from json file

I have json file with given data (total.json)
var data = {"trololo":{"info":"61511","path".... }}
I need to get object "info" and then print data "61511" in alert window
I include my json like
var FILE = 'total'
var data_file_names = {};
data_file_names[FILE] = 'total.json';
And then i use it like
var data_trololo = data_file_names[FILE];
Plese, help me print object "info". Maybe there is another way to solve this problem
You need to make an ajax call to the json file. Then you can access the array like the below example.
Note : Your json wasn't properly formatted.
var data = {
"trololo":{
"info": ["61511","path"]
}
};
console.log(data.trololo.info[0]); //this one will print 61511
Usually one can make an ajax call to read the file on the server.
But if you are ok with using HTML5 features then go through the link find out how to read the file on the browser itself. Though File API being part of HTML5 spec is stable across browsers.
http://www.html5rocks.com/en/tutorials/file/dndfiles/

AJAX post JSON data from Javascript to Grails

I'm trying to POST JSON formatted data from Javascript (using Prototype) to Grails. My Javascript code is:
var JSONObject = new Object;
JSONObject.id = "23";
JSONObject.name = "Test 1";
JSONstring = JSON.stringify(JSONObject);
var url = "${createLink(controller:'testController', action:'receiveJson')}";
new Ajax.Request(url, {
method:'post',
contentType:'application/json',
parameters:JSONstring,
asynchronous:true,
onSuccess: function (req) {
sendInfoResponse(req.responseText);
}
});
and the code in my Grails controller is:
def receiveJson = {
def json = request.JSON;
}
However, the 'json' variable appears to be empty in my tests. I'd be so grateful if someone could explain what I'm doing wrong. Many thanks.
In your Ajax.Request options change
parameters:JSONstring,
to
postBody:JSONstring,
The problem with using parameters is that it URL encodes the data so that the request body ends up looking like this:
%7B%22id%22%3A%2223%22%2C%22name%22%3A%22Test%201%22%7D&_=
Instead of the desired (which is what you get with postBody):
{"id":"23","name":"Test 1"}
Good question mfloryan - I was doing the testing manually, i.e. not as part of a unit or integration test.
Thanks very much for the help hvgotcodes. I made the changes to my code as you have suggested, but unfortunately to no avail. Interestingly, if I print request.JSON I get {}, whereas if I print request.json I get null.
EDIT: By 'printing' I mean using: request.JSON.toString()
EDIT: Thank you all so much for the help. Once I'd made the final change John Wagenleitne suggested the code began working properly. I'm very grateful indeed for all your help.
I don't think you are invoking the Ajax.Request correctly. From the documentation, the parameters option:
"The parameters for the request, which will be encoded into the URL for a 'get' method, or into the request body for the other methods. This can be provided either as a URL-encoded string or as any Hash-compatible object (basically anything), with properties representing parameters."
I think you need to do something like
...
parameters: {json: JSONString}
...
and then in your controller
request.json
note the form of the parameters object literal - it tells the Prototype library to make the request key 'json' and the request value be the json string. You access the key off the request object in the controller.
EDIT -- I just realized you're javascript block is jacked up.
This:
var JSONObject = new Object;
should be something like
var JSONObject = new Object();
...
you might also be able to do just an object literal, so
var jsonObject = {};
....

Categories