Json receive a request - javascript

Hi i have generate this
jsonWriter
.key(FEEDBACK)
.object()
.key(DOCUMENT)
.value(idDocument)
.endObject();
When it come it coming something like this : {"feedback":{"document":"0.23106060923811467"}
When i try to create the object json it gives me an error:
JSONTokener json = new JSONTokener(request.getParameter("id"));
Thanks in advance

Related

Flask: python object to json triggering error when read by javascript

I'm trying to pass python dictionaries and javascript objects back and forth as necessary. From similar questions, I've gathered that I need to do this.
Python:
posts = [
{'author':'JL Rowling','title':'Harry Potter'},
{'author':'JRR Tolkien','title':'Lord of the Rings'},
]
Javascript:
var jsonPosts = JSON.parse({{ posts }});
console.log(jsonPosts);
Likewise, these doesn't work either:
var jsonPosts = JSON.parse(posts|tojson);
var jsonPosts = {{ posts|tojson }};
The JS error I'm triggering is TypeError: Object of type Undefined is not JSON serializable
I got this advice from the following Q/A:
Python to Javascript JSON objects (Flask)
How can I pass data from Flask to JavaScript in a template?
How can I fix this?
Edit:
I've used answer recommendation and found the following error to be present in the console:
VM129:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at about:16
Corresponding to
let jsonPosts = JSON.parse();
It seems that it doesn't have access to encoded_posts.
You need to use the encoded posts:
encoded_posts = json.dumps(posts)
That will give you string, which is what JSON.parse is expecting.
var jsonPosts = JSON.parse({{ encoded_posts }});

Javascript - Read JSON fields that are formatted as urls

A REST API sends me JSON back with URLs as fields.
How do I read these fields with Javascript?
This doesn't work...
var json = JSON.parse(profile);
console.log(json["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality"]);
Error:
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at Strategy._verify (D:\Development\NodeJS\EID_TEST_NODEJS\server.js:33:21)
at validateCallback (D:\Development\NodeJS\EID_TEST_NODEJS\node_modules\passport-saml\lib\passport-saml\strategy.js:61:14)
at D:\Development\NodeJS\EID_TEST_NODEJS\node_modules\passport-saml\lib\passport-saml\saml.js:845:5
at _fulfilled (D:\Development\NodeJS\EID_TEST_NODEJS\node_modules\q\q.js:854:54)
at self.promiseDispatch.done (D:\Development\NodeJS\EID_TEST_NODEJS\node_modules\q\q.js:883:30)
at Promise.promise.promiseDispatch (D:\Development\NodeJS\EID_TEST_NODEJS\node_modules\q\q.js:816:13)
at D:\Development\NodeJS\EID_TEST_NODEJS\node_modules\q\q.js:624:44
at runSingle (D:\Development\NodeJS\EID_TEST_NODEJS\node_modules\q\q.js:137:13)
at flush (D:\Development\NodeJS\EID_TEST_NODEJS\node_modules\q\q.js:125:13)
JSON send back from the api:
{
"issuer":"www.econtract.be",
"nameID":"00081007501",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality":"Hasselt",
"be:fedict:eid:idp:card-validity:end":"2023-03-03T00:00:00Z",
"be:fedict:eid:idp:card-number":"592548451825",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/privatepersonalidentifier":"00081007501",
"be:fedict:eid:idp:nationality":"Belg",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dateofbirth":"2000-08-10T00:00:00Z",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/gender":"1",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/postalcode":"3511",
etc....
}
Problem solved! Thanks #Mike
Change this code:
var json = JSON.parse(profile);
console.log(json["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality"]);
To this code:
console.log(profile["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality"]);
Thanks for the help!
Observation :
You are trying to parse JSON Object. No need to parse JSON object again as it is already parsed while sending back from the API.
Working Demo
var profile = {
"issuer":"www.econtract.be",
"nameID":"00081007501",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality":"Hasselt",
"be:fedict:eid:idp:card-validity:end":"2023-03-03T00:00:00Z",
"be:fedict:eid:idp:card-number":"592548451825",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/privatepersonalidentifier":"00081007501",
"be:fedict:eid:idp:nationality":"Belg",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dateofbirth":"2000-08-10T00:00:00Z",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/gender":"1",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/postalcode":"3511"
};
console.log(profile["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality"]);

Extracting data from JSON with JavaScript

Probably a stupid issue, but I am stuck.
I have a node.js server that sends data to a client, like this:
var message_to_client = result;
socket.send(JSON.stringify(message_to_client));
Client succesfully receives the data; if I log it on console, it reads like this:
[{"_id":"55e60d3de4b06ef3ed5f189e","par1":54.2441033, "par2":-10.177503399999999}]
I want to show the par1 value on screen, however I don't seem to be able to 'extract' it from the JSON response.
I tried with the parseJSON function from jQuery and with https://stackoverflow.com/a/22628619/3849735, neither worked.
Anyone can help? Thanks.
Send the response in json format instead in string, like
var message_to_client = result;
socket.send(message_to_client);
client side
data[0].par1
will return the values

Strange JSON response (" "=> ,) in rails app

I'm getting a json response from the forecast.io api with
JSON.parse(open("https://api.forecast.io/forecast/api-key/latitude,longitude").read)
And it looks like this
{"latitude"=>58.5942,
"longitude"=>16.1826,
"timezone"=>"Europe/Stockholm",
"offset"=>2,
"currently"=>{
"time"=>1367829429,
"summary"=>"Clear",
"icon"=>"clear-day",
"precipIntensity"=>0,
"temperature"=>59.04,
"dewPoint"=>41.6,
"windSpeed"=>11.49,
"windBearing"=>224,
"cloudCover"=>0.08,
"humidity"=>0.53,
"pressure"=>1022.88,
"visibility"=>6.21,
"ozone"=>319.4
}
I'm new to json but this is not regular json right? What should I do to get this to my view in script tags?
Thanks.
Use the particular JSON Keymap you want in the call, and return it in the JSON request callback function. I believe that would resolve your problem.
response = HTTParty.get('https://api.forecast.io/forecast/api-key/latitude,longitude', {:timeout => 3})
#currenttemp = response["temp"]
it will return in a json object because it detects it is JSON. (HTTParty is just a helper gem)

Send JSON Object to Rails

Hi I'm new to rails so please bear with me :) I want to send JSON object to rails and save it to database. basically I have a data entered by the user then I have a javascript function thats retrieves the data and convert it into JSON object. What i want is to sent the JSON object maybe through ajax to rails and save it to the database.Can anyone give me any idea how to do it. thnx
function save(){
----(some codes)
notesArray.push({ Index: i, Title: title.val(), Content: content.val()});
// json encode it
var jsonStr = JSON.stringify(notesArray);
//want to add code here to send to rails
}
If you're using jQuery, it's very easy to do this using $.post():
$.post('/some/page/here', {notes: jsonStr});
As to "handle the JSON object in the controllers" you can use parsed_params = CGI.parse(params[:_json]) ,then you can get what you what througt parsed_params[key1][key2]

Categories