I was recently handed a partially-completed project and I'm new to using Bottle. I have a situation where I'm sending a dictionary inside an AJAX request and Bottle is on the server side. The dictionary looks something like this (in JavaScript):
var myInt = 5;
var myArray = [0, 1, 2];
var data = {
myInt: myInt,
myArray: myArray
};
Then, in Python, I want to read in this data. I can't seem to get the array. I can get the int just fine. I've tried several things, but here's what made most sense to me that still didn't work:
try:
myInt = int(request.forms.get('myInt'))
myArray = request.forms.getall('myArray')
This results in an empty list for myArray. Can anyone point me in the right direction? I've read every similar question on StackOverflow to no avail.
I know I could turn this into a string separated by pipes or something, but I would like to see if arrays are possible to send like this.
Thanks!
Use request.json:
try:
myInt = request.json['myInt']
myArray = request.json['myArray']
(Assumes your client is setting content-type to application/json.)
Here's a nice example.
Not sure whether this is the only problem, but (I think) you may be confusing JSON arrays and the use of getall. You should use get, not getall, here:
myArray = request.params.get('myArray')
If I understand the code correctly, getall is for the case when you have multiple args with the same name, as in http://example.com/get?foo=1&foo=2.
On the other hand, your myArray variable is just a single reference to an array.
Hope this helps (even if it doesn't solve your problem).
var myInt = 5;
var myArray = [0, 1, 2];
var data = {
myInt: myInt,
myArray: JSON.stringify(myArray)
};
Use JSON.stringify in js and in bottle json_loads():
myInt = request.params.get('myInt')
myArray = json_loads(request.params.get('myArray'))
Related
I have a PHP script to which I make an Ajax request, and most of it works okay, but I'm having trouble accessing an array in the data returned to the JavaScript function.
So, the PHP has a bunch of regular variables, and one array. The array, $places, has four elements, which each have three values, as so:
[["z","815","1"],["w","2813","0"],["s","1582","2"],["b","1220","5"]]
A relevant excerpt of the PHP script is:
$encoded_places = json_encode($places); // if I don't do this then I end up with a value of "Array"
$qobject->name = "$name";
$qobject->multi = "$multi";
$qobject->places= "$encoded_places";
$myJSON = json_encode($qobject);
echo $myJSON;
In the JavaScript script (using JQuery), I successfully obtain the data from the Ajax request, and I can access all the data okay, except the $places data.
$.getJSON(url, function(data, status){
var stringified = JSON.stringify(data);
var parsedObj = JSON.parse(stringified);
var x = parsedObj.name; // alert(x); // which works fine
var myArray = new Array();
myArray.push(parsedObj.places);
for(var i = 0; i < myArray.length; i++){
console.log(myArray[i]);
}
... and the console will display what I'm expecting, namely:
[["z","815","1"],["w","2813","0"],["s","1582","2"],["b","1220","5"]]
However, I'm having difficulty accessing these values. For example, supposing I try to access the "815" portion of the first element, with something like: myArray[0][1], all I end up with is "[".
I guess somehow this whole piece of data is just a string, instead of an array, but I'm not familiar enough with JavaScript to quite know how to progress.
If, for example, I do this in the JavaScript script (hoping to see 815, 2813, 1582 and 1220 in the alerts) all I'll see is the single alert with "[". (i.e. it does the loop only once, and selects the character in position 1).
for(var i = 0; i < myArray.length; i++){
console.log(myArray[i]);
alert(myArray[i][1]);
}
I would very much appreciate someone explaining:
(a) how I can access the individual elements and values in JS
(b) how I can loop through them, although presumably once it's an array and not a string then the code above should do this.
Many thanks for any assistance.
Now Resolved:
As noted by #charlietfl, below, using quotes in
$qobject->places= "$encoded_places";
screwed things up, along with using json_encode on $places. However, without removing the quotes nothing worked either way. So, removed quotes and just used json_encode on the entire structure at the end, which now works fine.
So, the original snippet of code, given above, now looks like:
$qobject->name = $name;
$qobject->multi = $multi;
$qobject->places= $places;
$myJSON = json_encode($qobject);
echo $myJSON;
Change
$qobject->places = "$encoded_places";
To
$qobject->places = $places;
And get rid of the $encoded_places = json_encode($places); so that the one call to json_encode serializes the whole structure
Try this:
$.getJSON(url, function(data, status){
var parsedObj = JSON.parse(stringified);
console.table(parsedObj.places);
console.log(parsedObj.places)[0][0];
}
In the posted code's getJSON context, data is already a JSON string. So this line is redundantly stringifying your JSON string:
var stringified = JSON.stringify(data);
stringified is now set to a literal/escaped version of the valid JSON string from the data parameter:
[[\"z\",\"815\",\"1\"],[\"w\",\"2813\",\"0\"],[\"s\",\"1582\",\"2\"],[\"b\",\"1220\",\"5\"]]
When that double-stringified value is passed to JSON.parse for the parsedObj reference, it just becomes the original JSON string again (which looks deceptively correct in an alert box).
Strings are iterable in JavaScript, so the for loop was just going over the string.
I am using IBM BPM 8.6
I have an input string as follows:
"\"RECORD_CONTACT\":\"Maram\" , \"DRUG\":\"Panadol\"
In a script on server side, I want to dynamically create a business object like this:
tw.local.recordContact = Maram;
tw.local.drug = Panadol;
How can I dynamically create the business object?
There are a few problems with your request. The first is that you are not creating a business object, you are creating variables. In IBM BPM the variables have to be declared at design time or you will get an error, so invoking attempting to call something like -
tw.local.myVariable = 'Bob';
Will throw an exception if tw.local.myVariable has not been declared. Base on your other question you asked here (link), I'm going to assume you actually have an ANY variable declared called "return" so that
tw.local.return.myVariable = 'Bob'
will work. Given that I based on Sven's answer I think something like the following will work (you will need to validate)
var str = "\"RECORD_CONTACT\":\"Maram\" , \"DRUG\":\"Panadol\"";
var jsonStr = "{" + str.replace(/\\\"/g,'\"') + "}";
var tempValue = JSON.parse(jsonStr);
var keyArray = Object.keys(tempValue);
var valueArray = Object.values(tempValue);
for(var keyCount=0; keyCount<keyArray.length; keyCount++{
var evalString = "tw.local.return."+keyArray[keyCount]+"="+valueArray[keyCount];
eval(evalString);
}
I'll note that doing this is a very bad idea as it would be very brittle code and that using eval() in this manner opens you up to all sorts of possible exploits. It will also fail badly if the value for one of the keys is not a simple type.
-Andrew Paier
One should know what you are going to do with dynamically created Business Objects (BO) to answer you better. Like a very generic way would be - creating JSON object instead of BO.
But if you want to stick with BO then this is only possible when you know all the BO structure (schema) beforehand during design time.
var str = "\"RECORD_CONTACT\":\"Maram\" , \"DRUG\":\"Panadol\"";
vat objArray = str.split("reg ex to split each object string")
foreach (obj in objArray ){
if(obj.indexOf( "RECORD_CONTACT")!=-1)
tw.local.recordContact = new tw.object.RECORD_CONTACT();
//below goes code get value of each attribute of BPM from string
}
else if(obj.indexOf( "DRUG")!=-1){
//similar code to create BO DRUG
}
Don't forget to create BO before using those :)
I am calling an API which is giving me back, among other things, an array of javascript objects. The objects in the array are named and I need to use the name in the new individual objects I am creating from the array. Problem is, I don't know how to get to the object's name.
{
"OldCrowMine.E9001":{"last_share":1524883404,"score":"0.0","alive":false,"shares":0,"hashrate":0},
"OldCrowMine.S9001":{"last_share":1524,"score":"648.24","alive":true,"shares":632,"hashrate":14317274},
}
I am after the "OldCrowMine.E9001" bit. I am sure this is quite simple, I just don't know how to search for the answer because I am not sure what to call this. I have tried searching for a solution.
Just loop - or am I missing something? Simplified raw data version.
var raw = {
"OldCrowMine.E9001":{"share":1524883404},
"OldCrowMine.S9001":{"share":1524}
};
for(var first in raw) {
console.log(first +" share -> "+ raw[first]["share"]);
}
var obj = {
"OldCrowMine.E9001":{"last_share":1524883404,"score":"0.0","alive":false,"shares":0,"hashrate":0},
"OldCrowMine.S9001":{"last_share":1524,"score":"648.24","alive":true,"shares":632,"hashrate":14317274},
}
console.log(Object.keys(obj)[0]);
Get the keys and map the name and the object:
var x= {
"OldCrowMine.E9001":{"last_share":1524883404,"score":"0.0","alive":false,"shares":0,"hashrate":0},
"OldCrowMine.S9001":{"last_share":1524,"score":"648.24","alive":true,"shares":632,"hashrate":14317274},
};
var mapped = Object.keys(x).map(function(d,i){return [d,x[d]]});
The name is map[n][0] and its object is map[n][1] where n is your item number.
I have an initial array (users) with multiple (string and numeric) arrays therein:
var users = [
['User: 10792 - Jack',45.7546,-117.807,2,'/res/smR11.gif'], ['User: 11248 - John',38.0867,131.976,3,'/res/smR08.gif']
];
I have a string of data from our server in the current form of:
newData = "['User: 18469 - Gary',-33.9399732539481,151.164383805489,3,'/res/markerw.gif'],['User: 10020 - Robert',40.6437563454472,-73.7593346140851,6,'/res/smR10.gif']";
I erase all existing data with users.length = 0;
I then need to insert the newData into the users array.
NOTE: I can obviously modify the server data into any other format
that would be more suitable.
Any help would be greatly appreciated.
try something like this
var users = JSON.parse(newData);
Your newData string looks very similar to the javascript above it. How about this...
users = eval('[' + newData + ']');
[EDIT]
As Bergi, rajeshkakawat and StephenJames pointed out, eval will work but is less secure.
See: JSON.parse vs. eval()
I have a cookie that stores 5 values separated by commas in one cookie. I'm able to retrieve the value of ExampleCookie as follows (as example):
var CookieValue = readCookie('ExampleCookie');
//returns Foo,Bar,Foo1,FooFighter,Bar2
How do I parse through CookieValue to assign individual variables such that I can assign a variable to each of the 5 parts?
I've found ways to do this with PHP but not javascript.
Thanks in advance for any advice.
use the String.split(delimiter) method
var array = readCookie('ExCook').split(",");
Reference:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split
You need to make an array from string:
CookieParams = CookieValue.split(",");
CookieParams[0] = Foo
CookieParams[1] = Bar
You could split the CookieValue into individual values in an array via the the split() method.
var valList = CookieValue.split(','); // ["Foo", "Bar", "Foo1", "FooFighter", "Bar2"]
If you then want the values to be assigned to individual variables, you would need to loop through the array and manually make the assignment.
JSON.stringify, and JSON.parse are your best cleanest bets (imho)
var values = JSON.parse(readCookie('ExampleCookie'));
createCookie('ExampleCookie',JSON.stringify(values));
This has the added benefit of being able to set key values in your object/array.
Assuming you're using the functions found at quirks mode just ensure your cookie values stringified don't go over the 4000 char limit found in most browsers.
I quickly realized this was more of a question on Split than about cookies. Here is what i came up w/.
var splits = ExampleCookie.split(",");
var slot1 = splits[0];
var slot2 = splits[1];
var slot3 = splits[2]; etc.