I am sending the array of dicts from javascript to python via a POST request that looks this way:
mydata.push({
department_id: department_id,
cardgroup_id: cardgroup,
doorgroup_id: doorgroup
});
$.post("data/save-office/"+office, {'data': JSON.stringify(mydata)}, function (data) {
console.log(data);
});
When extracting the payload in python:
departments = request.form.getlist('data')
The output is:
departments = ['[{"department_id":"1","cardgroup_id":"2","doorgroup_id":"2550"},
{"department_id":"2","cardgroup_id":"2","doorgroup_id":"2550"},
{"department_id":"3","cardgroup_id":"2","doorgroup_id":"2550"},
{"department_id":"4","cardgroup_id":"2","doorgroup_id":"2550"}]']
This displayed output is an array of one index and the inside is treated as a string rather than a dictionary.
How can I filter it or send it from javascript so that it can be decoded as an array of dicts not an array of strings?
Without changing your code, the simplest solution is using the json library's load or loads (load safe) method
import json
departments_string = request.form.getlist('data')[0]
departments = json.loads(departments_string)
print(departments)
[{'department_id': '1', 'cardgroup_id': '2', 'doorgroup_id': '2550'},
{'department_id': '2', 'cardgroup_id': '2', 'doorgroup_id': '2550'},
{'department_id': '3', 'cardgroup_id': '2', 'doorgroup_id': '2550'},
{'department_id': '4', 'cardgroup_id': '2', 'doorgroup_id': '2550'}]
I would further question using getlist, but we would need more deatils from you to deal with that.
Related
I am trying to achieve something rather simple, but i do not know why i am so stuck on it.
I want to send data to an parent function.
This data is only acceptable in a form of a string. But my issue here is that sometimes on click event i may have multiple strings
The final goals is to send them both up
setNewFruits('banana' , 'mango')
So on click i am getting my object
...
const foundFruits = foundFruitsCategory.fruits
console.log : {name: 'banana', id: 1, color: 'yellow'}
And the if i want to extract the name only i do :
const foundAndSelectedFruit = foundFruits.map((fruit) => fruit.name)
console.log output:
['banana']
But the thing is i want to have the name only as a string banana and not as array of strings.
Yes i can say
console.log(foundAndSelectedFruit[0])
That will give me the banana , but the thing is sometimes onClick i could have two objects
console.log output:
[
{name: 'banana', id: 1, color: 'yellow'}
{name: 'mango', id: 2, color: 'orange'}
]
So the log of foundAndSelectedFruit will be
['banana','mango']
How i can extract them as seperate strings and send them to my update function ?
( The function awaits a string of name )
P.S. I already tried with forEach loop , but instead of printing my string it gives me back undefined
Have you tried the spread operator?
setNewFruits(...foundAndSelectedFruit)
I'm trying to store some data in an associative array in php for access in javascript later. I want to process the data in such a way that I can access it in multiple ways, say both by name and by type?
//e.g. in cpp i would do
struct SortedFruits{
std::unordered_map<std::string, Fruits> byName;
std::unordered_map<std::string, std::unordered_map<std::string, Fruits&>> byType;
}
SortedFruit fruit();
//then add them like
fruit.byName["apple"] = new Apple();
fruit.byType["red"]["apple"] = &fruit.byName["apple"];
I basically just want fruits.byType['red']['apple'] === fruits.byName['apple'] somehow. Ideally I want this to be done in php so i can store it somwhere and not recomputed, but if references/pointers can't survive inside a json I'm happy doing the sorting in javascript as well.
May I ask what's the best way to do this?
I think formatting the datas in php that way to be parsed by js later from a json is not the best way to do.
Basically you have objects Fruit that have two properties name and color. I'd just encode a json with an array of Fruit and in js map it the way I want to use those objects.
I don't think mapping the objects is the responsability of the server, it's responsability is to give the client the datas.
Edit (in response of the comment)
In JS i would even not store them in multiple maps.
const fruits = [
{color: 'red', name: 'apple'},
{color: 'red', name: 'strawberry'},
{color: 'yellow', name: 'banana'}
];
const redOnes = fruits.filter(fruit => fruit.color === 'red');
// will return [{color: 'red', name: 'apple'}, {color: 'red', name: 'strawberry'}]
const apple = fruits.find(fruit => fruit.name === 'apple');
// will return {color: 'red', name: 'apple'}
In order to pass template variables to Amazon SES, templateData needs to be in the form of a string with escaped quotes, as the following:
"TemplateData": "{ \"subject\": \"mySubject\", \"date\": \"myDate\", \"header\": \"myHeader\", \"message\": \"myMessage\" }"
I need to pass data from a firestore document into these template values. I have tried using ES6's Template strings but the string is not being accepted as valid:
"TemplateData": `{ \"subject\": \"${createdData.subject}\", \"date\": \"${createdData.date}\", \"header\": \"${createdData.header}\", \"message\": \"${createdData.message}\" }`
Any ideas?
This should do it.
const createdData = {
subject: '1',
date: '2',
header: '3',
message: '4'
}
const string = JSON.stringify(createdData)
const escapedString = JSON.stringify(string)
I don t know why data formated as json using JSON.parse function return as Array type when I want to check the new converted type.
First I made ajax request to go and fetch data from a database as illustrated below
$.ajax({
url:'processBet.php',
data:'',
success:function(data){
//below I check the return data type
console.log( Object.getPrototypeOf(JSON.parse(data)));
//the return type is array.....why?
console.log((JSON.parse(data)); // to see the data
}
});
Obviously in the file that fetch data in the database will put data in Array.So before sending it I converted it in JSON using a php function json_encode as illustrated below
$ql = "SELECT * from tempdata" ;
$result=$pdo->query($ql);
$result->setFetchMode(PDO::FETCH_ASSOC);
while($data = $result->fetch()){
$arrays[]=$data;
}
//Now I convert in json before sending
$json =json_encode($arrays);
echo $json; // the return data supposed to be json type
Below is the sample of the data return after succeessfull ajax request
So Iwould like to know why the return type is still array and not JSON since a new conversion has been made when the ajax request succeed
The reason is because how you are setting up your array before encoding it.
$arrays[] = $data;
PHP will set it as an object if the depth of the elements go beyond just an array of arrays.
Example:
If you create a simple 2d array like this one:
$p = [
'name' => 'jack',
'job' => 'ceo',
'age' => 'old'
]; // {"name":"jack","job":"ceo","age":"old"}
You will have an Object in your JS code; That's because of the way PHP handles it. However, look at this example as an alternative: This will return an array of objects:
$p = [[
'name' => 'jack',
'job' => 'ceo',
'age' => 'old'
],[
'name' => 'sam',
'job' => 'cool',
'age' => 'decent'
]];
echo json_encode($p); //[{"name":"jack","job":"ceo","age":"old"},{"name":"sam","job":"cool","age":"decent"}]
It's all about that key placement. If you have a key => pair array it will become an Object no matter what. Look at another example of a simple JS array:
print_r(json_encode([
'burger',
'pizza'
])); // ["burger","pizza"]
But if you add just one key=>pair to your array it will become an json object:
print_r(json_encode([
'burger',
'pizza',
'people' => [
'jack' ,
'sam',
'pete'
]
])); // {"0":"burger","1":"pizza","people":["jack","sam","pete"]}
Just for educational purpose if you throw it inside another 1d array you will get an array objects:
print_r(json_encode([[
'burger',
'pizza',
'people' => [
'jack' ,
'sam',
'pete'
]
]])); // [{"0":"burger","1":"pizza","people":["jack","sam","pete"]}]
Explanation:
When dealing with an array, it will strictly handle it's key from 0 to however many items are in the array; so an array in json_encode terms is anything with a simple 1d interface:
Which in PHP & JavaScript would look like this:
PHP
print_r([
'burger',
'pizza'
]); // Array ( [0] => burger [1] => pizza )
Javascript
console.log([
'burger',
'pizza'
]); // Array [ "burger", "pizza" ]
When adding the key to your array and making it into a 2d or more complex json_encode will convert it to a JavaScript Object; as we saw in the first example:
I have the following javascript that sends data to a PHP function:
<script>
var mydata = {
id:123,
name: 'mike',
orders: []
};
$.ajax({
type: 'POST',
url: 'test.php',
data: {save_data:mydata},
success: function(data) {
alert('php received: ' + data);
}
});
</script>
and my test.php file contains the following code:
<?php
if (isset($_POST['save_data'])) {
$json = json_encode($_POST['save_data']);
echo $json; // just to check what has been received
exit();
}
?>
What I expect to received from PHP is:
{"id":"123","name":"mike","orders":"[]"}
What I got back is {"id":"123","name":"mike"}
Notice that orders array has been eliminated from the output. No place holder for it. I tried adding some dummy elements in the array, and that worked fine, and I received the array back with the elements.
I need PHP to receive the json object as is, even if it contains empty arrays.
How can I do that?
The JSON object is created inside PHP. Before then you just have form data.
jQuery will encode form data in a PHP-friendly style.
If you give it:
data: { foo: [1, 2, 3] }
It will convert that to:
foo[]=1&foo[]=2&foo[]=3
(although it will percent encode the [])
You get a key=value pair for each value.
If you have an empty array then you don't have any values, so you don't get any key=value pairs.
There is no way to encode "an empty array" using PHP's extensions to the form url encoding syntax.
You have two basic options:
Tell PHP about what data structure you want to create in advance and have it fill in the empty arrays.
Generate the JSON on the client
It is not error of PHP. It cause by Jquery will igrone empty array when send it to server. So you have to parse array in 'orders' key to string JSON before send
var mydata = {
id:123,
name: 'mike',
orders: []
};
Change to
var mydata = {
id:123,
name: 'mike',
orders: JSON.stringify([])
};