I've seen lots of articles on how to serialise arrays from javascript to send to PHP files which the PHP file will then deserialise back into an array, etc...
I have a large-ish nested associative array in my javascript which I need to save to a string and at a later date retrieve and convert back into a string in javascript. No other program will ever touch this. It may be handy if the serialised data is human-readable but it is absolutely not a requirement.
There is an intermediate PHP file but it's only 4 lines long: all it does is save the string to a file and send it back when requested. I'm not interested in parsing the array in PHP.
What is the fastest and simplest way to convert a multi-nested associative array in javascript to a string and back again?
JSON is a subset of the JavaScript language that is widely used as a serialization format, both for JavaScript and increasingly for other languages as well. It's human-readable, except that most implementations remove optional whitespace, which makes it a bit more difficult.
Modern browsers have JSON support out-of-the-box, for older ones you will need to include a library like json2.js.
To serialize, you use the JSON.stringify method.
var myObject = {a: 2, b: 3, c: [1, 2, 3]};
var serialized = JSON.stringify(myObject);
// serialized == "{"a":2,"b":3,"c":[1,2,3]}"
To unserialize, you use the JSON.parse method.
var recovered = JSON.parse(serialized);
Well, I have constructed my array like: var data = new Array(); data["John"] = "John Smith";
Ah, this is a problem. A JavaScript Array isn't meant to be used as an associative array, it's meant as a normal zero-indexed non-associative array. You can assign properties (key/value pairs) to any JavaScript object, which is why your code is working, but the fact thay your object is an Array is probably going to cause problems. If you just create a new Object() instead things should work better.
You'll want to serialize your array into JSON:
serialized = JSON.stringify(myobject)
To get it back
myobject = JSON.parse(serialized)
http://www.json.org/js.html
var someArray = [];
someArray.push({someObjectProperty: 'someValue' });
someArray.push({someObjectProperty: 'someValue2' });
console.log(someArray);
var stringVersion = JSON.stringify(someArray);//You can save the string version anywhere...
console.log(stringVersion);
var someNewArray = JSON.parse(stringVersion);
console.log(someNewArray);
Everyone has explained this well on the Javascript side, but this is how it happens on the PHP side:
<?php
$arr = Array(1, 2, 3, 'a', 'b', 'c'); // an array in PHP
echo json_encode($arr); // output the array as JSON: [1,2,3,'a','b','c']
?>
<?php
$json = "[1,2,3,'a','b','c']"; // a JSON string to be parsed by PHP
$arr = json_decode($json); // this is our original array in PHP again
?>
Related
I just realized that when I make a POST request like this:
async createProduct(){
let formData = new FormData();
formData.append("name", "test")
formData.append("price", 150)
formData.append("brands", [1, 2])
let response = await axios.post("/createProduct", formData)
}
And then console.log() the typeof each property on the back-end, I always get a string:
console.log(typeof req.body.brands) --> String 1, 2
console.log(typeof req.body.price) --> String 150
Why is this happening and how can I turn them to their original data types? I guess I can turn the req.body.price to integer with parseInt(), but how to turn req.body.brands back to an array?
I'm assuming you're using something like multer as a body parser to handle form-data.
You are adding the array wrong. The formData.append() function only accepts a string as argument. This causes [1,2] to be converted to a string automatically which conveniently is equal to [1,2].join(', ').
However, form-data does indeed support multiple values which multer will parse into arrays. But note that it support multiple values. Not arrays. So the correct syntax to add an array of values is:
formData.append("brands", 1);
formData.append("brands", 2);
Or more generally:
[1,2].forEach(x => formData.append("brands", x));
Doing this your backend should correctly parse the values into an array:
console.log(typeof req.body.brands) --> Array [1,2]
Your question is very confusing. How do you console.log() on the back-end?
If you meant, front-end and you are using PHP or whatever, if you receive an object response, you still have to convert it to your desired data type.
For JSON
var a = JSON.parse(response)
Then if you're expecting an array,
you should make the response an array type in the server. That way, Javascript will automatically detect it as an array.
console.log(response.length)
If you want convert your data to array in the server:
$data = array(1,2,3);
Then ensure you use a proper encoding type to flush response back to the HTML page.
echo json_encode($data);
If you already have your data and want to convert it to an array, do this:
var arr = [];
var data = response.split(',');
//Loop through data
for(var x=0;x < data.length;x++) {
arr.push(data[x]);
}
console.log(typeof arr) //Array (Object)```
Ordinarily, The ```arr = arr.split(',');```
is already an array and can be worked on
Here is my code:
I am getting data from mysql query and getting array of values. But i am not able to populate in javasript. could you please any one help me out...
PHP Code:
$parishFamilyInfo = $parishFamilyInfoBO->sendBirthdayGreeting($personalInfoSearchDO, $parishFamilyInfoSearchDO);
foreach ($parishFamilyInfo as $parishFamily){
if(!empty($parishFamily->email)){
print_r($parishFamily);
}
}
JavaScript:
$(document).ready(function(){
var t = $('#people').bootstrapTransfer(
{'target_id': 'multi-select-input',
'height': '15em',
'hilite_selection': true});
t.populate([ /*here i need to populate php array value*/
{
value:"<?php print_r($parishFamily->email);?>",
content:"<?php print_r($parishFamily->name);?>"
},
]);
//t.set_values(["2", "4"]);
//console.log(t.get_values());
});
print_r is only for debugging. It's not for anything else. Let me quote the documentation:
print_r — Prints human-readable information about a variable
As stated above, it is a debugging function that's used to print the contents of a variable in a more readable manner. It just returns a string — JavaScript does not and will not understand this format.
Use JSON (JavaScript Object Notation) instead. It is is a light-weight data interchange format that is very popular nowadays. You can use the built-in function json_encode to create the JSON representation of your PHP array and then transfer it to JavaScript. JSON being language independent and based on the JavaScript scripting language, your JavaScript code will now be able to parse the array:
t.populate([
{
value: <?php echo json_encode($parishFamily->email); ?>,
content: <?php echo json_encode($parishFamily->name); ?>
},
]);
For example I have the following code:
localStorage["screenshots"] = new Array();
localStorage["screenshots"]["a"] = 9;
alert(localStorage["screenshots"]["a"]);
Arr = new Array();
Arr["screenshots"] = new Array();
Arr["screenshots"]["a"] = 9;
alert(Arr["screenshots"]["a"]);
(I use Google Chrome v9.0.597.107 on Windows Vista 32-bit)
But only the second part works (output of alert() is "a")!
The first alert outputs in contrast "undefined"!
What is the problem?
Thanks.
localStorage stores values as strings, so you need to JSON serialize your objects on the way in and deserialize them on the way out. For example:
var data = {'A': 9};
localStorage['screenshots'] = JSON.stringify(data);
// Later/elsewhere:
var data = JSON.parse(localStorage['screenshots']);
// 9
console.log(data.A);
The localStorage object can only store strings. To store other types of data, use must convert them to strings, and convert them back on retrieval. In most cases you would want to use JSON to do this.
Local storage only stores string keys and string values.
The DOM Storage mechanism is a means through which string key/value pairs can be securely stored and later retrieved for use.
Source: MDC.
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.
This is royally annoying me at the moment:
Consider an array of 2 values:
var myArray = new Array();
myArray.push(21031);
myArray.push(21486);
When storing this in a cookie using jquery and toJSON, the value of the cookie looks like this:
["21031","21486"]
Now consider an array of a single value:
var myArray = new Array();
myArray.push(21239);
When storing this in a cookie using jquery and toJSON, the value of the cookie looks like this:
21239
This is almost completely useless to me as when I pull the items from the cookie, one comes back as a single value, the other comes back as an array that I can iterate over....ahhh!
Why?
I'd suggest using json2.js' JSON.stringify. It gets both of those cases right:
// [] is the same as new Array();
var foo = [];
foo.push(1);
foo.push(2);
JSON.stringify(foo); // "[1, 2]"
var bar = [];
bar.push(1);
JSON.stringify(bar); // "[1]"
In addition, when you use the json2.js API, your code automatically takes advantage of browser-native functionality in newer browsers.
You're doing something wrong. Regardless of what JSON lib you're using (presuming it actually works), serializing this:
[21031, 21486]
should produce this:
"[21031,21486]"
Not ["21031","21486"] as you've posted. That looks like you're serializing the individual elements. Post more code.
Cookies are strings, so all you are doing is storing a string serialisation of the array. If I do:
document.cookie = [1, 2].toString()
then document.cookie has the value "1,2", which is not an array.
EDIT: as toJSON isn't a native jQuery method, it presumably comes from a plugin. Have you checked the plugin documentation? Alternatively, try a different plugin that works as you expect.