This question already has answers here:
Reverse of JSON.stringify?
(8 answers)
Closed 7 years ago.
I need to convert Javascript object to string and then this string back to object.
Objects i get like that:
var Checked = {};
// Hold all checkboxes
$('div.list input[type=radio]:checked, input[type=checkbox]:checked').each(function () {
var $el = $(this);
var name = $el.attr('name');
if (typeof (Checked[name]) === 'undefined') {
Checked[name] = [];
}
Checked[name].push($el.val());
});
I know how to do this with array by using join and split, but how to be with objects?
Now how to convert this object to string?
How to get back this string to object?
Here you are:
var object = {
"1": [1, 2, {
3: "3"
}]
};
var str = JSON.stringify(object);
console.log(str);
var obj = JSON.parse(str);
console.log(obj["1"][2][3]);
Hope this helps.
The JSON.parse() method parses a string as a JSON object, optionally transforming the value produced by parsing.
Syntax
JSON.parse(text[, reviver])
Parameters
text
The string to parse as JSON. See the JSON object for a description of JSON syntax.
reviver Optional
If a function, prescribes how the value originally produced by parsing is transformed, before being returned.
Returns
Returns the Object corresponding to the given JSON text.
Throws
Throws a SyntaxError exception if the string to parse is not valid JSON.
The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.
Syntax
JSON.stringify(value[, replacer[, space]])
Parameters
value
The value to convert to a JSON string.
replacer (Optional)
A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string.
space (Optional)
A String or Number object that's used to insert white space into the output JSON string for readability purposes. If this is a Number, it indicates the number of space characters to use as white space; this number is capped at 10 if it's larger than that. Values less than 1 indicate that no space should be used. If this is a String, the string (or the first 10 characters of the string, if it's longer than that) is used as white space. If this parameter is not provided (or is null), no white space is used.
Source:
JSON.parse()
JSON.stringify()
var obj = { x: 5, y: 6 };
var a = JSON.stringify(obj);
console.log(typeof a);
console.log( a);
var b = $.parseJSON(a);
console.log(typeof b);
console.log( b);
Related
let arr = [1,2,3];
let empArr =[];
for(var i =0; i< arr.length;i++){
console.log('First',typeof empArr);
empArr+=arr[i];
console.log('Second',typeof empArr)
}
The above code gives this output
First object
Second string
First string
Second string
First string
Second string
Could anyone explain how in first iteration type was Array Object then after that it became string.How Javascript Engine works here?
If we run typeof empArr, we will see empArr an object. No matter if we declare it as an array, internally, it is an object. Further, typeof arr[i] shows arr[i] is a number. Therefore, empArr+=arr[i] means we are trying to add an object and a number. Since we are trying to add two different types, it can happen with the help of coercion, implicitly. Coercion means, converting a value of one type to another. JavaScript performs implicit coercion as per the following rules:
operand + operand = result
If at least one operand is an object, it is converted to a primitive
value (string, number or boolean);
After conversion, if at least one operand is string type, the second operand is converted to and the concatenation is executed;
In other case both operands converted to numbers and arithmetic addition is executed.
Note that the primitive value of an array or object is a string.
In our case, empArr is of type object and by rule 1, it is coerced as a string. Now by rule 2, the arr[i] which is a number, is coerced to a string as well and get assigned to empArr.
For more details:
JavaScript addition operator in details
JavaScript type coercion
According to javascript,
typeof [] is "object" ,i.e., every array is actually an object.
if you append anything to a string it will become a string
"1"+1 will equal "11"
It's because of auto type conversion.
The += is a not an array operator, and as the second operand is string - the 1st is converted to string.
Use empArr.push(arr[i])
Given:
var obj={0:21,1:22}
and
var arr=[21,22]
Why does parseInt(obj) return NaN, but parseInt(arr) returns 21?
I had a function where I was either going to pass an int, a hash type object or a plain array. I was expecting parseInt to return NaN for both object and array, thus simplifying argument checking. What gives?
This is because parseInt tries to coerce the first argument to a string before parsing to an integer. String(obj) returns "[object Object]" and can't be parsed, but String([21,23]) returns "21,23", which parseInt parses until it reaches the unparseable char.
See the parseInt spec:
Let inputString be ? ToString(string).
(Coerce the input to a string).
If S contains a code unit that is not a radix-R digit, let Z be the substring of S consisting of all code units before the first such code unit; otherwise, let Z be S.
(Drop any part of the string starting with non-digit character, so "21,23" -> "21").
I get an error with the following code. I know $.parseJSON() is sensitive to single/double quotes. I cannot think of a solution to this problem. Can you please help !
<div data-x='{"a":"1","b":"2"}'></div>
$(document).ready(function(){
var data =$.parseJSON($("div").data("x"))
alert(data.a)
})
https://jsfiddle.net/r2Lnfbpm/
jQuery's data() does type conversion, so when the data attribute is valid JSON, it's already parsed into an object, and passing an object to $.parseJSON produces an error, as it expects a string of JSON.
$(document).ready(function(){
var data = $("div").data("x");
console.log(data.a);
});
From the documentation
Every attempt is made to convert the string to a JavaScript value
(this includes booleans, numbers, objects, arrays, and null).
A value is only converted to a number if doing so doesn't change the value's
representation.
For example, "1E02" and "100.000" are equivalent as
numbers (numeric value 100) but converting them would alter their
representation so they are left as strings. The string value "100" is
converted to the number 100.
When the data attribute is an object (starts with '{') or array
(starts with '[') then jQuery.parseJSON is used to parse the string;
it must follow valid JSON syntax including quoted property names. If
the value isn't parseable as a JavaScript value, it is left as a
string.
To retrieve the value's attribute as a string without any attempt to
convert it, use the attr() method.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Convert JS object to JSON string
Store comma separate values into array
I have a string containing values separated with commas:
"1,4,5,11,58,96"
How could I turn it into an object? I need something like this
["1","4","5","11","58","96"]
This will convert it into an array (which is the JSON representation you specified):
var array = myString.split(',');
If you need the string version:
var string = JSON.stringify(array);
In JSON, numbers don't need double quotes, so you could just append [ and ] to either end of the string, resulting in the string "[1,4,5,11,58,96]" and you will have a JSON Array of numbers.
make it an array
var array = myString.split(',');
Simple question -
How do I convert a string that has been through parseInt back to it' string value?
var myInt = parseInt('J', 36); //19
var myString = myInt.toString(); //returns "19" I would like it to return "J"
Can I do it with longer strings?
var myInt = parseInt("Jon o'reiley", 36); //25511
When converting a string to an int, information of the base the string used is lost. Also any data that was ignored while parsing is lost.
However, just like parseInt toString has a base argument, too:
myInt.toString(36);
Demo from the JS shell:
js> (19).toString(36)
"j"
js> parseInt('abc+foo', 36).toString(36)
"abc"
You can't.
Once an object has been converted to an integer, any other information is lost.
You would have to store J in a seperate object if you wish to access this later.