I want to post a variable through AJAX.
The typeof variable is "object".
If I directly post an object, the AJAX fails. I used JSON.stringify but then it’s in ["10","11","12"] format.
I need a string similar to 10,11,12. How do I do that?
Just call method join on your array like this :
console.log(["10","11","12"].join(",")); // 10,11,12
The String() function converts the value of an object to a string. The String() function returns the same value as toString() of the individual objects.
function myFunction() {
var x1 = ["10","11","12"];
var res = String(x1) + "<br>";
document.getElementById("demo").innerHTML = res;
}
<p>Click the button to convert object to string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
Seems like this was an array so toString() should do it.
but ["10","11","12"] was the correct representation of the javascript object.
[] tells it was an array, that information is permanently lost when you generate something like 10,11,12
Related
I tried to write some javascript code that multiplies with number salaries of each person, and makes them into string with JSON.stringify.
For example, in salaries, the name and the original salary are in here like this:
let salaries = {
james:100000,
john:200000,
jane:300000
};
and I want to express like this: {james:110000,john:220000,jane:330000}
So, I wrote the code like...
let payjson = JSON.stringify(pays, function replacer(key, value){
return value*1.1;
}); // 1st try
and got an error, the values are changed like [object Object], NaN.
However, this code just worked for me
let payjson = JSON.stringify(pays, function replacer(key, value){
return Number.isInteger(value)? Math.floor(value*1.1): value;
}); // 2nd try
I wonder why the first one didn't work the way I wanted and the second just worked the way I wanted to.
As the stringify() function documentation clearly explain, the replacer function is initially passed the object, and then each of the properties. So, you are seeing this behavior. The first time when the value comes in as object type, and the multiplication is attempted, it crashes and does not subsequently pass the properties, so the overall return of the stringify() is null. In your 2nd try code, you are checking the value and only if it is of numeric type, you are doing the math and returning a calculated value, which is used by stringify() to append to the output string.
See the documentation, and mainly this paragraph :
Initially, the replacer function is called with an empty string as key representing the object being stringified. It is then called for each property on the object or array being stringified.
It looks like you want to create a copy of the original object with 10% higher salaries:
const salaries = {
james:100000,
john:200000,
jane:300000
};
const res=Object.fromEntries(Object.entries(salaries).map(([k,v])=>[k,1.1*v]));
console.log(res);
// this can be strigified too:
console.log(JSON.stringify(res));
// and the input object is unchanged:
console.log(salaries);
When the replacer function is first called, key is assigned an empty string. However, the function is still expected to return value, otherwise it terminates.
let salaries = {
james:100000,
john:200000,
jane:300000
};
document.write(JSON.stringify(salaries,(k,v)=>{return k==''?v:Math.floor(v*1.1);}));
I have not worked too much on javascript. And, I need to parse a JSON string. So, I want to know what exactly JSON.parse does. For example :
If I assign a json string to a variable like this,
var ab = {"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}};
Now when I print 'ab', I get an object.
Similarly when I do this :
var pq = '{"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}}';
var rs = JSON.parse(pq);
The 'rs' is the same object as 'ab'. So what is the difference in two approaches and what does JSON.parse did differently ?
This might be a silly question. But it would be helpful if anybody can explain this.
Thanks.
A Javascript object is a data type in Javascript - it's have property and value pair as you define in your first example.
var ab = {"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}};
Now What is Json : A JSON string is a data interchange format - it is nothing more than a bunch of characters formatted a particular way (in order for different programs to communicate with each other)
var pq = '{"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}}';
so it's is a String With json Format.
and at last JSON.parse() Returns the Object corresponding to the given JSON text.
Here is my explanation with a jsfiddle.
//this is already a valid javascript object
//no need for you to use JSON.parse()
var obj1 = {"name":"abcd", "details":"1234"};
console.log(obj1);
//assume you want to pass a json* in your code with an ajax request
//you will receive a string formatted like a javascript object
var str1 = '{"name":"abcd", "details":"1234"}';
console.log(str1);
//in your code you probably want to treat it as an object
//so in order to do so you will use JSON.parse(), which will
//parse the string into a javascript object
var obj2 = JSON.parse(str1);
console.log(obj2);
JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML.
Your 'ab' variable isn't a string, it is a proper javascript object, since you used the {} around it. If you encased the whole thing in "" then it would be a string and would print out as a single line.
Data Type!! That is the answer.
In this case, ab is an object while pq is a string (vaguely speaking). Print is just an operation that displays 'anything' as a string. However, you have to look at the two differently.
String itself is an object which has properties and methods associated with it. In this case, pq is like an object which has a value: {"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}} and for example, it has a property called length whose value is 66.
But ab is an object and you can look at name and details as its properties.
What JSON.parse() did differently was that, it parsed (converted) that string into an object. Not all strings can be parsed into objects. Try passing {"name":"abc" and JSON.parse will throw an exception.
Before parsing, pq did not have any property name. If you did something like pq.name, it'll return you undefined. But when you parsed it using JSON.parse() then rs.name will return the string "abcd". But rs will not have the property length anymore because it is not a string. If you tried rs.length then you'll get a value undefined.
I have variable in javascript which is coming from php by json_encode.
While I am psrsing it with JSON.parse(variable). It alert me objects instead of actual result.
CODE:
var a = '<?php echo json_encode($over_branch_array); ?>';
a = JSON.parse(a);
alert(a);
EDIT:
basically I need to map my php array.
a = a.map(function(v){
return { id : v.branch, text : v.branch };
});
If I will do JSON.stringify then I won't be able to do that..
alert performs a toString conversion on objects before displaying them. You'll get a result like this.
If you want to view the contents of the object, either console.log it or JSON.stringify it.
EDIT:
When I say use JSON.stringify I mean do it to show what is actually in the object:
alert(JSON.stringify(a));
I have a 2-D php array which i am encoding through JSON. My 2d array in php is something like this:
$array['A'][12] = 8;
$array['A'][8] = 21;
$array['B'][17] = 19;
$array['B'][9] = 12;
when I do echo json_encode($array); and alert this as Ajax xmlhttp.responsetext i get this in my alert box : {"A":{"12":"8","8":"21"},"B":{"17":"19","9":"12"}}
which is absolutely fine. Now i need to parse it in javascript so i used the JSON.parse() function. The problem is when i access the A and B fields of the string. I get this in my alert boxes: Object object. How to parse this associative array? I am a beginner in AJAX and JSON so please help.
var array = JSON.parse(yourResponseData);
array.A // Object
array.A['12'] //8
You can't access the key '12' via the dot syntax becase no variable name can start with a number.
You can use console.log() rather than alert() to see the complete structure of that parsed json object.
You can easily retrieve the value by using . notation or [] brackets:
For example:
var returned = JSON.parse(tran.responseText);
console.log(returned['A']['8']); //which should give you '21' based on your case
A website returns the following JSON response, how would I consume it (in javascript)?
[{"ID1":9996,"ID2":22}]
Is JSON simply returning an array?
We use:
function evalResponse(response) {
var xyz123 = null;
eval("xyz123 = " + response);
return xyz123;
}
An alternative method is to simply use:
var myObj = eval(response);
Basically, you have to call eval() on the response to create a javascript object. This is because the response itself is just a string when you get it back from your AJAX call. After you eval it, you have an object that you can manipulate.
function myCallback(response) {
var myObj = evalResponse(response);
alert(myObj.ID1);
}
You could use a javascript library to handle this for you. Or, you could try to parse the string yourself. eval() has it's own problems, but it works.
If you use http://www.JSON.org/json2.js you can use it's method JSON.parse to retrieve the json string as an object (without the use of eval (which is considered evil)), so in this case you would use:
var nwObj = JSON.parse('[{"ID1":9996,"ID2":22}]');
alert(nwObj.ID1); //=> 9996
It looks like an array with a single object holding two properties. I'd much prefer to see the same data structured like this:
{"ID":[9996,22]}
Then you have a single object holding an array with two elements, which seems to be a better fit for the data presented. Then using Endangered's evalResponse() code you could use it like this:
var responseObj = evalResponse(response);
// responseObj.ID[0] would be 9996, responseObj.ID[1] would be 22
I think the other answers might not answer your question, maybe you're looking for a way to use that "array of 1 object". Maybe this can help:
var arr = [{"ID1":9996,"ID2":22}];
var obj = arr[0];
var id1 = obj.ID1;
var id2 = obj.ID2;
Here's how you get to your data:
<script type="text/javascript" >
var something = [{"ID1":9996,"ID2":22}]
alert(something[0].ID1)
</script>
The JSON you posted represents an array containing one object, which has attributes ID1 and ID2 (initialized to the respective values after the colon).
To convert the string to a javascript object, pass it to eval, like this:
var obj = eval('[{"ID1":9996,"ID2":22}]');
However, this method will fail if you only have a single object instead of an array, so it is safer to wrap it in parenthesis:
var obj = eval('(' + jsonResponse + ')');