how to avoid Special characters to Create Json object in Javascript? - javascript

In my Java script I'm create array and now I'm converting to Json Object using stringify method.
<script type="text/javascript">
var array1 = new Array();
$.ajax({
url : "Result",
type : 'POST',
data : {
"array1" : JSON.stringify(array1),
"globalClassId" : globalClassId
}});
</script>
But in server side array1 parameter creating like ["1","2","3"] But we don't want extra bracket []
How to Remove this extra bracket?
If we remove this extra [] the code look like "1","2","3" ,
we can simple loop it.

Following code working for me..
<script type="text/javascript">
var array1 = new Array();
$.ajax({
url : "Result",
type : 'POST',
data : {
"array1" : array1.join(),
"globalClassId" : globalClassId
}});
</script>

Replace
JSON.stringify(array1)
With
JSON.stringify(array1).splice(1, -1)
Keep in mind that you might as well re-add the square brackets on the server-side in order to parse the results correctly as JSON. If you're wanting to use custom logic to interpret the data, make sure to correctly handle escaped characters.

I was having the same problem, So used the following code...Hope it will suffix your requirement.
JSONObject obj = new JSONObject(request.getParameter("names"));
List<String> list = new ArrayList<String>();
JSONArray array = obj.getJSONArray("interests");
for(int i = 0 ; i < array.length() ; i++){
}

Related

iOS Swift How to pass JSON String and Array or Dictionary to Javascript from UIWebView?

In my project I have pass String to JavaScript using stringByEvaluatingJavaScript it have passed successfully. But if I have pass JSON String and Array or Dictionary means it doesn't pass the values I don't know how to pass these.
Here I have mention the code I have tried for pass the string to JavaScript,
let param:String = "HI"
let _ = self.webView.stringByEvaluatingJavaScript(from: "myNewFunction('\(param)')")
It Successfully return the value HI
Here I Mentioned the JavaScript Code,
<!DOCTYPE html>
<html>
<p>Click the button to display an alert box.</p>
<script>
function myNewFunction(param) {
alert(param);
}
</script>
<body>
<button onclick="myNewFunction()">Try it</button>
</body>
</html>
How can I pass the values like Array and Dictionary and the JSON String?
let dict:[String:Any] = ["key1":10,"key2":false, "key3": "Some string goes in here"]
let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: [.prettyPrinted])
if let data = jsonData{
let value = String(data: data, encoding: .utf8)
print( value )
}
Output:
Optional("{\n \"key1\" : 10,\n \"key2\" : false,\n \"key3\" : \"Some string goes in here\"\n}")
Code in Playground
Result in Playground
Here what was missing was the dictionary type inference i.e dict:[String:Any]. Also when you use try use optional along with it as it may throw an exception like try?
This might work.. I haven't tested it yet:
if let data = try? JSONSerialization.data(withJSONObject: arrayOrDictionaryHere, options: [.prettyPrinted]), let param = String(data: data, encoding: .utf8) {
self.webView.stringByEvaluatingJavaScript(from: "myNewFunction('\(param)')")
}
//JS:
function myNewFunction(param) {
alert(JSON.parse(param))
}
Use following code for converting dictionary to jsonstring:
var dict : Dictionary = ["key1":"value1","key2":"value2"]
let data = try JSONSerialization.data(withJSONObject: dict, options: [.prettyPrinted])
let value = String(data: data, encoding: .utf8)
and then call your javascript method using the string in value
if you replace dict in second line with and instance of json array then you will get json string of the json array too. I every thing will work for that too.

Send object array to node/Parse to Json

I'm trying to send object array to node.
If i'm sending it without stringify, i'm getting an array with the same length that i sent, but empty (["", ""]);
if i send it with JSON.stringify , this it the result:
{'[{"itemNumber":"13544","currentShelf":"1A1","amount":"1","newShelf":"","actionType":"in","whareHouse":"Main"},{"itemNumber":"13544","currentShelf":"1B1","amount":"1","newShelf":"","actionType":"in", "whareHouse":"Main"}]': '' }
This is how i'm sending it:
for (var i=1; i<=m; i++){
itemIdTemp= document.getElementById("itemIdShell"+i).value;
shellTemp= document.getElementById("id_shell"+i).value.toUpperCase();
newShellTemp= document.getElementById("id_shell_new"+i).value.toUpperCase();
shellAmountTemp = document.getElementById("amountShell"+i).value;
itemAmount=0;
let itemData={
itemNumber:itemIdTemp,
currentShelf:shellTemp,
amount:shellAmountTemp,
newShell:newShellTemp,
actionType:direction,
whareHouse:"Main",
};
console.log(itemData);
itemsObject.push(itemData);
}
console.log(itemsObject);
$.post('/itemShell/updateMulti',
JSON.stringify(itemsObject),
function(data){
console.log(data);
});
The object contain a string of the array and i can't get it.
I tried Json.Parse(), it won't work in this case.
any suggestions?
Have a look at this example code
const jsObjectArray = [
{name: "Homer", age:56 },
{name: "Marge", age:50 },
];
const buf = JSON.stringify(jsObjectArray);
console.log("Stringified object: "+buf);
//
// Now convert it back to an object
//
const newObject = JSON.parse(buf);
console.log("Reconstituted object: "+newObject);
It's in this codepen too:
https://codepen.io/mikkel/pen/KRayye
I found the problem.
It must be declare as JSON type when post to Node, so u need to use ajax:
$.ajax({
url: '/itemShell/updateMulti',
type:"POST",
data:JSON.stringify(dataTosend),
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(){}
}
and i also change it to object type like this:
dataToSend={dataArr:itemsObject}
So in node it's appearing as array
My Guy work a little bit on the string before sending it
First get the string the stringify is returning
var json_string = JSON.stringify(itemsObject);
var string = json_string.replace("'", "\'");
string = '{\'[{"itemNumber":"13544","currentShelf":"1A1","amount":"1",
"newShelf":"","actionType":"in","whareHouse":"Main"},
{"itemNumber":"13544","currentShelf":"1B1","amount":"1",
"newShelf":"","actionType":"in", "whareHouse":"Main"}]\': \'\' }';
first_str = string.split("': "); // remove the last useless chars
second = first_str[0].substring(2, first_str[0].length); // remove the first two chars
$.post('/itemShell/updateMulti', second,
function(data){
console.log(data);
});
the second should have the correct string.
GOODLUCK

Getting null in when trying to get array in servlet

I have a below set of code to get the table data in an array and pass the same to servlet through ajax call. But i am getting null. Please someone help me on what my mistake / how to get the required data since i am new to this servlet and web app. So far i tried with some examples given in SO. but i am clueless to get my expected data.
var myTableArray = [];
$("table#itemtable tr").each(function() {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function() { arrayOfThisRow.push($(this).text()); });
myTableArray.push(arrayOfThisRow);
}
});
alert(myTableArray);
$.ajax({
url:"insertmasteritem",
type:"POST",
dataType:'json',
data: {json:myTableArray},
success:function(data){
// codes....
},
});
Servlet code
String[] myJsonData = request.getParameterValues("json[]");
System.out.println("myJsonData.length"+myJsonData.length);
for (int i = 0; i < myJsonData.length; i++) {
String[] innerArray=myJsonData[i].split(",");
System.out.println(myJsonData[i]);
}
Send your Json data like this
$.ajax({
url:"insertmasteritem",
type:"POST",
dataType:'json',
data:myTableArray,
success:function(data){
// codes....
},
});
and In Servlet Class
JSONObject jsonObj= new JSONObject(request.getParameter("myTableArray"));
Iterator it = jsonObj.keys();
while(it.hasNext())
{
String jsonKey = (String)it.next();
String jsonValue = jsonObj.getString(jsonKey);
System.out.println(jsonKey + " --> " + jsonValue );
}
Well, you need to send a properly formatted JSON object (as a string) to the servlet. Possibly the easiest way to do this is to create some javascript objects and fill an array with these objects. The array data should then be
converted to a JSON string (using JSON.stringify). I'm going to hardcode object values (but you will get them from your table)
Javascript code
function generateJson(){
var myObjArr = [];
//you will typically have just one object (e.g. myObj, which you will fill in your ajax table loop
//myObj.v1 = v1_val;
//myObj.v2 = v2_val;
...
//myObjArr[i] = myObj; //
myObj1 = { "v1": "Orange", "v2": "ABC", "v3":10,"v4":"OK" };
myObj2 = { "v1": "Apple", "v2": "XYZ", "v3":25,"v4":"OK" };
myObjArr[0] = myObj1;
myObjArr[1] = myObj2;
var jsonObjStr = JSON.stringify(myObjArr);
//you can now use jsonObjStr to send your data to the servlet
// document.getElementById("json").innerHTML = jsonObjStr;//this is just added for testing purposes
}
The generated JSON
[{"v1":"Orange","v2":"ABC","v3":10,"v4":"OK"},{"v1":"Apple","v2":"XYZ","v3":25,"v4":"OK"}]
As you can see, the json string starts with a [ (which denotes an array). You may have to change this to start with a { (and with a } ) depending on how your JSON parser works ({} denote an object).
For the servlet part, it depends on the actual JSON parser you're using. Try to use some of the suggestions provided by others. I can provide some code using Jackson though, but you will have to add the Jackson library to your classpath.
why you are getting parameter value as JSON[]
String[] myJsonData = request.getParameterValues("json[]");

Replacing values in JSON object

I have the following JSON object data returned from my apicontroller :
[
{"id":2,"text":"PROGRAMME","parent":null},
{"id":3,"text":"STAGE","parent":2},
{"id":4,"text":"INFRA","parent":2},
{"id":5,"text":"SYSTEM","parent":3},
{"id":6,"text":"STOCK","parent":3},
{"id":7,"text":"DPT","parent":3},
{"id":9,"text":"EXTERNAL","parent":null}
]
I want to replace "parent":null with "parent":'"#"'
I have tried the code below, but it is only replacing the first occurrence of "parent":null. How can I replace all "parent":null entries?
$(document).ready(function () {
$.ajax({
url: "http://localhost:37994/api/EPStructures2/",
type: "Get",
success: function (data) {
var old = JSON.stringify(data).replace(null, "'#'"); //convert to JSON string
var new = JSON.parse(old); //convert back to array
},
error: function (msg) { alert(msg); }
});
});
Thanks,
You need to make the replace global:
var old = JSON.stringify(data).replace(/null/g, '"#"'); //convert to JSON string
var newArray = JSON.parse(old); //convert back to array
This way it will continue to replace nulls until it reaches the end
Regex docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
Also, as a side note, you should avoid using new as a variable name as it is a reserved word in javascript and most browsers will not allow you to use it
#JonathanCrowe's answer is correct for regex, but is that the right choice here? Particularly if you have many items, you'd be much better off modifying the parsed object, rather than running it through JSON.stringify for a regex solution:
data.forEach(function(record) {
if (record.parent === null) {
record.parent = "#";
}
});
In addition to being faster, this won't accidentally replace other nulls you want to keep, or mess up a record like { text: "Denullification Program"}.

Parse XML into Javascript Object

I am grabbing data from a Google spreadsheet through the Google API using cURL in PHP. Using a AJAX HTTP request (via jQuery) I can pull all the data in and get it into an array, but since the <content> tag looks like dirty JSON I'm a little stuck.
I would like to be able to reference the data as a JS object, like so:
alert(xml.feed.content.name);
Example Code:
$.ajax({
type: "GET",
url: GtargetURL,
dataType: "xml",
success: function parseMyXML(xml){
var Entries = new Array;
var i = 0;
$(xml).find("entry").each(function(){
var content = $(this).find("content").text();
Entries[i]=content;
i++;
});
var myArray= new Array();
myArray= Entries[1].split(",");
alert (myArray[1]); // Result: "test2"
}
});
Example XML:
<feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:gsx=
<entry>
<content type='text'>relativeid: 4, name: test2, type: teset3, multiples: yes, cat: yes</content>
</entry>
<entry>many more entries...</entry>
</feed>
Thanks for any help you can offer.
For what it's worth, I am using this URL format for the Google api call:
https://spreadsheets.google.com/feeds/list/KEY-ID-HERE/1/public/basic
I know that I can do a "cell" call instead of a "list" call, but this suits my purposes better.
You could do something like this: http://jsfiddle.net/GVUnF/ http://jsfiddle.net/rMMkD/1/ in your loop.
var jsonLikeString = "name:red, type:blue, multiples:green, cat:brown";
var jsObject = {};
var stringWithoutSpaces = jsonLikeString.split(' ').join('');
var splitStrings = stringWithoutSpaces.split(",");
var kvPairArray = [];
for(var i in splitStrings){
if(splitStrings.hasOwnProperty(i)){
var kvPair = splitStrings[i];
kvPairArray = kvPair.split(":");
jsObject[kvPairArray[0]] = kvPairArray[1];
}
}
alert(jsObject.cat);
Please note that
var foo = new Array;
is not exactly idiomatic in javascript.
You should use
var foo = [];
instead.
Also, for appending to an array you should use
foo.push('something');
instead of having a variable i and incrementing it every loop.
There are two parts to your question:
How to turn XML into JSON
How to turn some text in XML that is almost JSON into JSON
To make XML into JSON you can use a library like http://www.thomasfrank.se/xml_to_json.html
It turns
<animals>
     <dog>
          <name>Rufus</name>
          <breed>labrador</breed>
     </dog>
     <dog>
          <name>Marty</name>
          <breed>whippet</breed>
     </dog>
     <cat name="Matilda"/>
</animals>
Into
{"animals":
{"dog":[
{"name":"Rufus",
"breed":"labrador"},
{"name":"Marty",
"breed":"whippet"}],
"cat":
{"name":"Matilda"}}}
Then you can follow the suggestion from TheShellfishMeme to turn
relativeid: 4, name: test2, type: teset3, multiples: yes, cat: yes
Into a JSON object

Categories