I have the following fiddle http://jsfiddle.net/kc11/h6nh1gvw/1/ . I'm not experienced with JS.
I see that ;
alert(JSON.stringify(getCarData()[0]));
produces :
{"car":"Mercedes A 160","year":2006,"available":true,"comesInBlack":"yes"}
but:
alert(JSON.stringify(getCarData())[0]);
produces:
[
Could someone explain in plain english what is happening here? Intuitively I feel that the second operation should work in producing the first JSON record as well.
In your first line of code you provide you are serializing an object and getting the result as a JSON string. The second example it seems you were trying to treat that object as an array and serialize the first element of that array that comes back.
Assuming this is the case you need to alter the location of the parenthesis in your code to be:
alert(JSON.stringify(getCarData()[0]));
What you wrote will actually just take the first character from the JSON string returned (which is "["). Hence the output that you get from this.
One other thing that is noteworthy here though is the fact that you aren't going to get what you expect when you index an object. You probably should specify a property name that you hope to serialize, something like:
alert(JSON.stringify(getCarData()["car"]));
You get the point. Best of luck!
Lets break down what alert(JSON.stringify(getCarData())[0]); is trying to do.
Remeber PEMDAS? We are basically doing the same thing.
The deepest parenthesis call is getCarData(), which returns the array.
Next, you call JSON.stringify() on that array, which returns a string.
And finally, you call [0], which effectively grabs the first character of that string.
Assuming JSON.stringify doesn't throw an error, the result of JSON.stringify(foo) is a String, let's call this str, so
JSON.stringify(getCarData())[0];
// same as
JSON.stringify(foo)[0]; // foo = getCarData()
// same as
str[0];
So by using the [0] here you're getting the first character from a String. This will be a "[" if you've stringified an Array
Now we understand this, let's look back at JSON.stringify(foo[0]), assuming foo is Array-like.
The [0] here is selecting the item at index 0 of the array, let's call this item, so
JSON.stringify(getCarData()[0]);
// same as
JSON.stringify(foo[0]); // foo = getCarData()
// same as
JSON.stringify(item);
// so we end up with
str2; // not the same as str
This time we have stringified something from JavaScript but not done anything further, so the result is the JSON representation of whatever we called stringify on (in your case it was an Object)
getCarData() is an array of objects.
getCarData()[0] is the first object of this array of objects, so it can be stringified.
JSON.stringify(getCarData()[0]) will return a string of the the first object of the array of objects.
JSON.stringify(getCarData()) will return a string of the entire array of objects.
JSON.stringify(getCarData())[0] will return the first letter of the string produced by the above command, which is [, because you're essentially doing something like "hi"[0] which is a character, whereas previously you did {"hi","hello"}[0] which is a string element.
There is a fundamental difference between the two orders of operations, which I will explain below.
TLDR
The first call to JSON.stringify() you do gets the car data you want and then stringifies it, while the second way stringifies an array of objects containing car data and then tries to access the first element in that string, which is the first character of that string.
Let's break down what the following line is doing:
alert(JSON.stringify(getCarData()[0]));
First
getCarData()
returns and Array that has an object in it at position 0. The [0] is saying give me the first item from the array of car data returned by getCarData().
You then pass this object to the JSON.stringify() function to be stringified. This works as you expect returning:
{"car":"Mercedes A 160","year":2006,"available":true,"comesInBlack":"yes"}
The second stringify call you make:
alert(JSON.stringify(getCarData())[0]);
is getting the car data (which is returned as an array) and passing it to the JSON.stringify function.
JSON.stringify(getCarData())
This will return an array of objects containing car data. JSON then tries to stringify the array, and returns
[{"car":"Mercedes A 160","year":2006,"available":true,"comesInBlack":"yes"},{"car":"Citroen C4 Coupe","year":2008,"available":false,"comesInBlack":"yes"},{"car":"Audi A4 Avant","year":2011,"available":true,"comesInBlack":"no"},{"car":"Opel Astra","year":2004,"available":false,"comesInBlack":"yes"},{"car":"BMW 320i Coupe","year":2011,"available":false,"comesInBlack":"no"}]
Next you try to access the first item in this stringified array, but since it is now a string (not an array) it just returns [, the first character of the string.
In conclusion
The first way you do it gets the data you want and then stringifies it, while the second way stringiness an array of objects containing car data and then tries to access the first element in a string, which is the first character of that string.
Related
This is sample JSON I got {"valueofa" : 1234}.To print the value it is something like body.valueofa. However, this valueofa can be anything like apple or something else. So to parse that I object I had tried with ${body}.${value} which isn't working and it's shouldn't be. How can I set the variable with body. So that I can parse the body whatever the value is.
If your object always contains only one key value pair like shown in the question, and you don't care about the key, you can just use Object.values()
console.log(Object.values({"valueofa" : 1234})[0]);
console.log(Object.values({"apple" : 1234})[0]);
The same is true for objects holding multiple key value pairs, Object.values() will return an array of all the values in your object if you omit accessing the first element with [0]
You can access a value of JSON using square brackets.
var value = "valueofa";
body[value];
I have created array in a object,
var obj_report_dailog = { array_report_dailog : [] }
Then push data to object,
obj_report_dialog.array_report_dialog.push({from: fromDate})
obj_report_dialog.array_report_dialog.push({to: toDate})
obj_report_dialog.array_report_dialog.push({fabrika: fabrika})
Then,
var json = JSON.stringify(obj_report_dialog);
How can I access to elements of that object?
console.log("işte bu: " + json);
output:
işte bu: {"array_report_dialog":[{"from":"2017-08-01"},{"to":"2017-09-21"},{"fabrika":["Balçova"]}]}
Two things:
You don't want to JSON.stringify unless you're sending the resulting string somewhere that will parse it. Remember, JSON is a textual notation for data exchange; JSON.stringify gives you a string to send to some receiver. When you have the JSON string, you don't access the properties of the objects in it.
If you're receiving that JSON string, you'd parse it via JSON.parse and then access the properties on the result.
Leaving aside the JSON thing, you probably don't want to add data the way you're adding it. You're adding three separate objects as three entries in the array, each with one property. You probably want to push one object with all three properties:
obj_report_dialog.array_report_dialog.push({
from: fromDate,
to: toDate,
fabrika: fabrika
});
Then you'd access them as obj_report_dialog.array_report_dialog[0].from, obj_report_dialog.array_report_dialog[0].to, and obj_report_dialog.array_report_dialog[0].fabrika. Or more likely, you'd have a loop like this:
obj_report_dialog.array_report_dialog.forEach(function(entry) {
// Use entry.from, entry.to, and entry.fabrika here
});
(See this answer for more options for looping through arrays.)
But, if you really want to push them as separate objects, you'd access them as obj_report_dialog.array_report_dialog[0].from, obj_report_dialog.array_report_dialog[1].to, and obj_report_dialog.array_report_dialog[2].fabrika (note the indexes going up).
If you stringify a json, it's gonna create a string representation of your object.
To access data in a string like that we usually use JSON.parse that create an json object from a string. Which is the obj_report_dailog you had at start.
You can make object from json by using JSON.parse()
JSON.parse(json).array_report_dialog
I have a javascript MAP object which is holding key as a string and value as a javascript array, each array is holding set of strings inside it. I want to convert the map of arrays into a json object in javascript.
Here is the code which i tried
function addRole() {
var jsonObjectOfMap={};
subMenuSelectedIdMap.forEach(function(items,key,subMenuSelectedIdMap){
jsonObjectOfMap[key]=JSON.stringify(items);
});
alert(JSON.stringify(jsonObjectOfMap));
I am getting the json object as like this
{"1004":"[1005,1006,1023]","1007":"[1008,1053]"}
But is this json format object is valid and what i have to do if i want it the format as this:
{"1004":["1005","1006","1023"]","1007":["1008","1053"]}
Please help me out
If the inner-most values are all numbers and you want them as strings in the end result, you'll have to convert each number individually to a string.
You can do that with another loop over each items using .map() and either calling String() or .toString() for each number:
subMenuSelectedIdMap.forEach(function (items, key, subMenuSelectedIdMap){
jsonObjectOfMap[key] = items.map(function (item) {
return String(item); // or `return item.toString();`
});
});
Optionally, since String() only acknowledges one argument (with the other two that .map() passes being ignored), the loop over items could be shortened to:
jsonObjectOfMap[key] = items.map(String);
Based on referencing the method/object definitions on MDN I am trying to construct a layman's step by step explanation of how the following script (from the previous post) is working to help my understand of it (and hopefully so I can adapt it further)
There's a few things I don't get so my attempt will probably seem a bit muddled but hoping someone can put me right where I'm off track/confused ...
(n.b. the encode function is just to encode html and required from node.js package)
var arr = {
"a": "Some strings of text",
"b": "to be encoded",
"c": "& converted back to a json file",
"d": "once they're encoded"
}
var encodedValues = Object.keys(arr).reduce(function(out,key) {
return Object.assign(out, {[key]: endcode(arr[key])})
}, {});
console.log(encodedValues);
Explanation
Create a variable “encodedValues” which will:
1 Object.keys(arr)
loop over and return the object arr’s properties in the order they are provided
2 .reduce(function(out,key)
First applying the following function to execute on each value in the array ("and reduce it to a single value" *):
3 return Object.assign(out, {[key]: endcode(arr[key])})
The function copies the values of all properties from the source object to a target object we will call “out”.
4 The source object has an encoding function {[key]: encode(arr[key])} applied to it so that where key is an object encode is applied to its property
5 }, {});
I assume this part , {} is the initialValue for .reduce i.e. the value used as the first argument to the first call of the callback, which starts as an empty object?
6
Object.keys returns an array (of the given object arr's encoded properties in the order they were provided)
7 which is then logged to the console
*I don't understand how or why we "reduce it to a single value" in this case??
Doesn't that suggest a concatination of the values is part of the process:
"Some strings of text" + "to be encoded" + "& converted back to a json file" + "once they're encoded". I don't really get how or why this is part of the working solution
Thanks!
What reduce() does is loop over the array, call your function for each item, and each time, it passes your function the return value of the previous iteration so that you can "build upon" it.
For example, you could use reduce() to total up an array of numbers. The iterator function would take in the running total, add to it, and then return the new total. Or, you could use it to concatenate a bunch of strings, where the iterator takes in the existing string, concatenates something onto it, and then returns the new string.
In this case, you're simply taking in an object (the parameter named out), doing stuff to it, then returning it so that the next iteration can keep working on it. When reduce() gets through all the keys, it will return the object you've been building upon. That goes into your encodedValues variable.
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.