Send JSON Data From JavaScript to a Servlet - javascript

... I am experiencing an anomaly that I do not understand why.
The scenario is as follows:
1.- From JSP, using JS, I send data in JSON format to a servlet.
JSON: "{'ORDER': '1', 'DATE': '06-01-2018', 'TIME': '07:06:51', 'BOUCHER': '208896.0', 'LIC' : 'HSGR30', 'QTY': '0.0'} "
2.- I capture the data, with the getParameter utility, on a String type variable.
3.- I pass the variable to the JSONObject utility, and it does not process it since there are two "" (two double quotes) in that variable, and debugging the class (JSONObject) throws an exception because the first character of the string is not "{" ... which is logical.
4.- Now, if I take the complete stream and paste it in the call:
JSONObject obj = new JSONObject ("{'ORDER': '1', 'DATE': '06-01-2018', 'TIME': '07:06:51', 'BOUCHER': '208896.0' , 'LIC': 'HSGR30', 'QTY': '0.0'} ")
It processes it correctly and I get the object with its associated properties and values.
I was considering that the JSON format I send from JS is not valid???. But I can't find the cause of why???
The problem is that I don't understand why two double quotes appear.
If you can give me a hand with this,
thank you very much !!!

use double quotes: " instead of single quotes: ' and use \ before each doublquote to escape the characters.
E.g:
JSONObject obj = new JSONObject ("{\"ORDER\": \"1\",\"DATE\": \"06-01-2018\",\"TIME\": \"07: 06: 51\",\"BOUCHER\": \"208896.0\",\"LIC\": \"HSGR30\",\"QTY\": \"0.0\"}");

Very grateful for your prompt replies.
I found the problem, in the js code I was doing JSON.stringify(). I remove it and everything is fine.
I just need to rethink how to send, from js, package JSON formatted records.
It was not clear how JSONObject handles the string it receives.
I guess I'll have to rethink an array of JSON objects and then send it. Perhaps, by receiving array object type, it will understand that it is a batch of records.
Thanks again

Related

Reactjs : Remove outer quotes from JSON after using JSON.stringify

I am using JSON.stringify on a Json data and after doing this I am getting the " (quotes) at the starting and ending of the data. For eg :
x = {fieldId: 536, value: {value: 341, display_value: "ABCD"}}
after using JSON.stringify i am getting :
x = "{"fieldId":536,"value":{"value":341,"display_value":"ABCD"}}"
but the result I desired is "
x = {"fieldId":536,"value":{"value":341,"display_value":"ABCD"}}
I have tried JSON.parse after stringify but of no use.
If you want an object
In the first code block in your question, you show your JS source code.
In the third code block, you show some more JS source code and say that it is what you want.
The two bits of source code give identical results. They just use very slightly different JavaScript syntax (in an object literal a property name can be an identifier (like foo) or a string (like "foo"), which you use makes no difference to the end result).
If you really do want what is in the third code block, then do nothing.
Do not use JSON.stringify.
If you want JSON
Your second block shows what you say you get after using JSON.stringify.
This result is impossible.
The most likely explanation for this is that you are inspecting the result using a tool which displays a quote before and after the data as a means to indicate to you that the value is a string. The quote characters are not part of the data. You are just misinterpreting what you are seeing.
If you really want a JSON representation of the data in the first code block, then just use JSON.stringify.
var x = {fieldId: 536, value: {value: 341, display_value: "ABCD"}};
var json = JSON.stringify(x);
document.write(json);

JSON parse functions are not parsing

I am running a Javascript function on the latest version of Mozilla which receives a string which I want to convert to a JSON object. The conversion seems to be failing.
The string is being generated on the server side in a Java function:
result = "[{ \"userID\": 1 \"firstName\":\"John\" \"lastName\":\"Sheridan\" }{ \"userID\": 2 \"firstName\":\"Michael\" \"lastName\":\"Geribaldi\" }]";
(note that I am attempting to return an array of values for a list).
The code on the client side is the ajax callback shown below:
var successFunc = function(data, textStatus, jqXHR)
{
alert("Data: "+data);
var obj = $.parseJSON(data);
alert("Object: "+obj);
}
Apparently, the data is coming back to the callback and is being displayed in its string form, but the JSON parser is failing because the second alert is failing to appear. I am sure something is wrong with my string but am having trouble figuring out what. The debugger is not telling me anything, I am just seeing a silent failure.
I have also attempted this using the JSON.parser() function. I am seeing the same thing. I am making a mistake somewhere. Can someone tell me where?
Your json is not valid, you are missing comma
In order to parse your json should be like this
[
{ "userID": 1, "firstName":"John", "lastName":"Sheridan" },
{ "userID": 2, "firstName":"Michael", "lastName":"Geribaldi" }
]
JSON is a format where data is in key:value pairs separeted by , and key and value are enclosed in double quotes, where objects are enclosed in {} braces and array is enclosed in [] hope you have got the your mistake that where your json is lacking.
"[{
\"userID\": 1 ,
\"firstName\":\"John\",
\"lastName\":\"Sheridan\",
},
{
\"userID\": 2 ,
\"firstName\":\"Michael\",
\"lastName\":\"Geribaldi\" }]"

JSON decode list of lists in Django Python

I have a list of lists (e.g. [[1,2],[3,4]]) passed from a Django view to a javascript variable and submitted with jQuery. I need to parse that variable to pull indices. The basic process is:
Add as context variable (python):
resultMsgList.append(msg)
resultMsgListJson=json.dumps(resultMsgList)
resultDict['resultMsgListJson']= resultMsgListJson
Javascript:
var resultMsgList = {{resultMsgListJson}};
var data = {'resultMsgList':resultMsgList};
$.post(URL, data, function(result){
});
Google Console gives me:
Javascript:
var resultMsgList = [["View \"S03_2005_LUZ_140814_105049_with_geom\" was successfully created!", "luz_mapfile_scen_tdm_140814_105049", "S03_2005_LUZ_140814_105049_with_geom", "C:/djangoProjects/web_output/mapfiles/ATLANTA/luz_mapfile_scen_tdm_140814_105049.map", [25, 50, 498.26708421479, 131137.057816715]]];
I copied this result to a validator, which states it is correct JSON.
The post gives me:
resultMsgList[0][]:View "S03_2005_LUZ_140814_105049_with_geom" was successfully created!
resultMsgList[0][]:luz_mapfile_scen_tdm_140814_105049
resultMsgList[0][]:S03_2005_LUZ_140814_105049_with_geom
resultMsgList[0][]:C:/djangoProjects/web_output/mapfiles/ATLANTA/luz_mapfile_scen_tdm_140814_105049.map
resultMsgList[0][4][]:25
resultMsgList[0][4][]:50
resultMsgList[0][4][]:498.26708421479
resultMsgList[0][4][]:131137.057816715
I need to get elements from this list. I currently have (python):
resultMsgListContext = request.POST.get('resultMsgListJson','')
resultMsgListContext = json.loads(resultMsgListContext)
oldMapfileName=resultMsgListContext[0][2] (+ a number of similar statements)
According to this post I then need to decode the variable in python with json.loads(), but it says there is no JSON object to be decoded. Based on the examples in the Python docs, I'm not sure why this doesn't work.
I believe the problem is that it is viewing the entire resultMsgList as a string, substantiated by the fact that there is a u' xxxxx ' in the result. That's why it is saying index out of range because you're trying to access a 2D array when it is still a string. You have to convert it to an array of strings by using json.loads.
In javascript, try passing
var data = {'resultMsgListJson':resultMsgList};
instead of
var data = {'resultMsgListJson': resultMsgListJson};
resultMsgListJson isn't a javascript variable that's defined at that point, it might be getting evaluated to undefined.
In general, in python, print the contents of resultMsgListContext before trying to do json.loads on it so you can see exactly what you're trying to parse.

JSON.parse parsing JSON with nested objects

I'm attempting to parse a JSON string with nested objects received in the response of a post request. After running JSON.parse(responseText), the result is in the following format:
[{
"atco":"43000156407",
"location":{
"longitude":"-1.7876500000000000",
"latitude":"52.4147200000000000","
timestamp":"2013-03-19 11:30:00"
},
"name":"Solihull Station Interchange",
"road":"STATION APPROACH",
"direction":"NA",
"locality":"Solihull",
"town":"Solihull"}, ...
I thought I would then be able pull values out using the following as an example, but all I get is undefined.
var atco = json[0].atco;
I've also tried json[0][0] but that returns an individual character from the JSON ([) . Does this indicate the JSON hasn't parsed correctly, or is this expected behaviour and I'm just referencing incorrectly?
This means that your JSON is being double encoded. Make sure you only encode it once on the server.
As proof, after you've parsed it, parse it again.
var parsed = JSON.parse(resposneText);
var parsed2 = JSON.parse(parsed);
alert(parsed2.atco);
Either that, or you're parsing it but then trying to select the data from the original string. This would obviously not work.

How to send js array via ajax?

I can only send string or numeric values,how to send an array?
You'll probably get a slew of answers all saying "JSON".
Here are some case specific examples. 'data' holds what you send.
var numArray = [17, 42, 23];
data = '[' + numArray + ']';
var strArray = ['foo', 'bar', 'baz'];
data = '["' + numArray.join('", "') + '"]';
For the general case, use a function that recursively encodes objects to JSON. If you really want me to, I'll post an example implementation, but it's a fun project so you might want to give it a try. If you're using a Javascript library, it might have a JSON encoder of it's own (such as jQuery's serializeArray).
There's are no built-in JSON serializers in javascript so you will need to use a library. A good one is json2.js.
Here's a sample:
// suppose you have an array of some objects:
var array = [{ prop1: 'value1', prop2: 10 }, { prop1: 'value2', prop2: 20 }];
// convert it to json string:
var jsonString = JSON.stringify(array);
// TODO: send the jsonString variable as a parameter in an ajax request
// On the server side you will need a JSON deserializer
// to convert values back to an array of objects
I can only send string or numeric values
Actually you can only send strings. When you include a number it is just turned into a string; it's up to the server-side script to parse that back into a number if it wants to.
how to send an array?
The native HTML-forms way of sending multiple values is using multiple inputs. You can reproduce this by including the same named parameter multiple times. To send [1,2,3]:
http://www.example.com/ajax.script?a=1&a=2&a=3
The same multiple-parameter-instance query string can be sent in an AJAX post request.
If you are using a higher-level framework to create the form-encoded string, it depends on the framework how it accepts multiple parameter instances. For example with jQuery you can post an object like {a: [1,2,3]}.
The other way is to forget the standard HTML form encoding and just pass all your values in whatever special encoding you like that allows you to retain datatypes and structure. Usually this would be JavaScript value literals (JSON):
http://www.example.com/ajax.script?a=%5B1%2C2%2C3%D
(that is, [1,2,3], URL-encoded.) You then need a JSON parser on the server to recreate native array values there.
You can actually send Arrays in a much cleaner way instead of trying to encoding JSON.
For example, this works
$.post("yourapp.php", { 'data[]': ["iphone", "galaxy"] });
See http://api.jquery.com/jQuery.post/ for more.

Categories