Parse XML into Javascript Object - javascript

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

Related

Loop function on Apps Scripts & Google Natural Language API

I am learning how to code so sorry if this is too basic, but I am getting troubles here:
I've been trying to invoke the Google Natural Language API, to give me information about information on 210 rows of my Google Spreadsheet (the whole table has 211 rows). I would like to save the results on 1 Json File.
I am trying to run a loop with the code below, but I am getting the Json file only with the information corresponding to the 1st row. Tried as well to put the "Driveapp.createFile line of code" inside of the loop function, but then I have many Json files, each one with the information corresponding to one row. And what I would like is 1 Json file, with the corresponding information of the 210 rows.
I would appreciate your help, please.
function analyzeText() {
var client = "Spreadsheet_ID";
var query = SpreadsheetApp.openById(client).getSheetByName("1. Template");
var result = SpreadsheetApp.openById(client).getSheetByName("Teste - Natural Language API");
var lrow = query.getLastRow();
for(var i=2; i<=211;i++)
{
var text = query.getRange(i,211).getValue()
var requestUrl = [
'https://language.googleapis.com/v1beta2/documents:analyzeEntities?key=',
'API_KEY_XXXXXXXXXXXXXXXXXXX'
].join("");
var data = {
"document": {
"language": "en-us",
"type": "PLAIN_TEXT",
"content": text
},
"encodingType": "UTF8"
};
var options = {
method : "POST",
contentType: "application/json",
payload : JSON.stringify(data)
};
var response = UrlFetchApp.fetch(requestUrl, options);
var data = JSON.parse(response);
}
DriveApp.createFile('response3.json', response, MimeType.PLAIN_TEXT);
}
I would suggest you instead of the approach you are taking (using a for loop and the method getValue(), which it's a slow method to call in a loop), consider this one I am giving you with this code:
function analyzeText() {
var clientId = "your-sheet-id";
var ss = SpreadsheetApp.openById(clientId);
var templateSheet = ss.getSheetByName("1. Template");
// .getRange(row, column, numRows) -> From the first row and col, take the next 4 rows
// Modify these arguments depending in where you want to start and how many rows you want
var data = templateSheet.getRange(1, 1, 4).getValues();
// You will get an array 2D, using join you will able to get an string from
// all the elements in that array
var text = data.join();
var requestUrl = [
'https://language.googleapis.com/v1beta2/documents:analyzeEntities?key=',
'API_KEY_XXXXXXXXXXXXXXXXXXX'
].join("");
// Now text will have all your cell values and you only need to do one request
var data = {
"document": {
"language": "en-us",
"type": "PLAIN_TEXT",
"content": text
},
"encodingType": "UTF8"
};
var options = {
method : "POST",
contentType: "application/json",
payload : JSON.stringify(data)
};
var response = UrlFetchApp.fetch(requestUrl, options);
var data = JSON.parse(response);
DriveApp.createFile('response3.json', response, MimeType.PLAIN_TEXT);
}
In this way, you only need to make one request and it will be faster than running 211 times your loop. I would also recommend you to check:
Apps Script Quotas: Running your code as you have it, it would give you more chances of hitting these quotas.
Best Practices: You can check more about the best practices so you can have a better idea about why I was telling you to avoid the getValue() method in a loop.

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[]");

how to avoid Special characters to Create Json object in 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++){
}

Reading C# dictionary in Javascript

I have a dictionary variable in C# (ASP.NET). I want to send this data to Javascript. I am using this code to serialize it and send to javascript.
Dictionary<string, string> chat;
chat = new Dictionary<string, string>();
chat.Add("Sam", "How are you?");
chat.Add("Rita", "I am good");
var serialize = new System.Web.Script.Serialization.JavaScriptSerializer();
Response.Write(serialize.Serialize(chat));
On the Javascript page, I am calling this page using this;
$.ajax({
url: "TextChatCalls/getChat.aspx",
type: "POST",
context: document.body,
success: function (response) {
var Chats = response.split('\n')[0];
alert(Chats);
}
});
The value in Chats var is {"Sam":"How are you?","Rita":"I am good"}
I don't know how do I read this value in Chats. Can I anyhow convert this into a 2D array and read it as array[0][0], array[1][0] etc. ?
Thanks.
EDIT:
One more confusion is that, the response object, returned from ASP.NET, contains
{"Sam":"How are you?","Rita":"I am good"}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
</title></head>
<body>
<form name="form1" method="post" action="getChat.aspx?Id=141755" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MTY2ODcyMjlkZJctiKZK4rXVndR3mbGssIarCrOF" />
</div>
<div>
</div>
</form>
</body>
</html>
And not just {"Sam":"How are you?","Rita":"I am good"} as expected. And hence I have to split the response object by var Chats = response.split('\n')[0]; which makes it an string!
You read like this:
alert(Chats["Sam"]);
(so like a C# Dictionary :-). You read/write to it using something like Chats["propertyName"])
or, to go through each value:
for (var c in Chats)
{
if (Chats.hasOwnProperty(c))
{
alert(c + ' ' + Chats[c]);
}
}
Note that this is different than C#. In C# c would contain a KeyValuePair<> containing both the key and the value. In Javascript c is only the key and to get the value you have to use Chats[c].
(the reasoning for hasOwnProperty is here http://yuiblog.com/blog/2006/09/26/for-in-intrigue/)
Now... If you really want to split it:
var array = [];
for (var c in Chats)
{
if (Chats.hasOwnProperty(c))
{
array.push([c, Chats[c]]);
}
}
Just add the data type json to your ajax request
$.ajax({
url: "TextChatCalls/getChat.aspx",
type: "POST",
dataType: "json"
context: document.body,
success: function (response) {
// do something with response
});
This will make response a javascript object that you can access like this
alert(response["sam"]) //How are you?
to split that up into a 2d array just do this
var Chats = [];
for ( k in response ){
Chats[Chats.length] = [k, response[k]];
}
I guess the important point here is that you properly understand what is going on on the JavaScript client side. The datatype that arrives on the JavaScript client side is a JSON string. JSON (= JavaScript Object Notation) can directly be interpreted by JavaScript.
A JavaScript object looks as follows:
var anObject = { name: "Sam", surname: "abc"};
You can access the properties of a JavaScript object either through a somewhat Dictionary-similar way like
anObject["name"] //will get "Sam"
or directly (property notation)
anObject.name
Instead a similar JSON string would look like
var aJsonString = '{ "name": "Sam", "surname": "abc"}'
Now to convert the JSON string to a JavaScript object you need to parse it. jQuery does this already for you, otherwise you can invoke JSON.parse(aJsonString) and you'll get a valid JavaScript object.
Here I did a quick example: http://jsbin.com/adejev/2/edit
For ASP.NET Core, I used this inside the cshtml file. Basically I rebuilt the entire Dictionary into Javascript. The reason for this approach is because I have subfunctions in Javascript that won't be able to call the server model functions with dynamic parameters on events like keypress.
var ModelZxcvWarnLookup = {};
#foreach (var kvp in Model.View.ZxcvbnWarningMsgLocalization)
{
#:ModelZxcvWarnLookup['#Html.Raw(#kvp.Key)'] = '#Html.Raw(#kvp.Value)';
}
Inspecting the html page fetched by the browser:
var ModelZxcvWarnLookup = {};
ModelZxcvWarnLookup["Straight rows of keys are easy to guess"] = "Chinese Straight rows of keys are easy to guess";
ModelZxcvWarnLookup["Short keyboard patterns are easy to guess"] = "Chinese Short keyboard patterns are easy to guess";
ModelZxcvWarnLookup['Repeats like "aaa" are easy to guess'] = 'Repeats like "aaa" are easy to guess';

Categories