I was following this article (https://www.visualstudio.com/docs/integrate/extensions/develop/add-dashboard-widget) to create a widget to add it to microsoft dashboard.
In my html file, there is this piece of code that I cannot get to work:
...(some code above)
return TFS_Wit_WebApi.getClient().getRevision(284,6)
.then(function (query) {
var $list = query.rev;
var $container = $('#query-info-container');
$container.empty();
$container.append($list);
... (some code below)
In this line:
var $list = query.rev;
I'm trying to get access to .json file "rev" variable.
Here is my .json file
{
"count": 15,
"value":
[
{
"id": 284,
"rev": 1,
"fields": {
"System.WorkItemType": "User Story",
"System.State": "New",
"System.Reason": "New",
"System.CreatedDate": "2016-06-23T14:31:37.567Z",
},
...(some code below)
And I'm able to get access to this "rev" variable.
However, now I want to get access to "fields", namely to
"System.State": "New",
Instead of
var $list = query.rev;
I tried
var $list = query.fields.System.WorkItemType[0];
And
var $list = query.value.fields[0];
and
var $list = query.fields;
However, that did not work.
Here is some documentation on how it is supposed to be accessed
fields: {[key: string]: any}.
But it is not much of a help.
Any help will be greatly appreciated!
Thank you!
You can use JSON objects as a kind of "map", what means they are composed of key-value pairs.
var $list = query.fields['System.State'];
There are many different ways of accessing a JSON object properties, as you have already mentioned in your question. However, if the property contains a dot or a space on its name, you need to fall back to the array notation. This means that the following attempts will yeld the correct result:
query.fields
query[fields]
query.fields['System.State']
query[fields]['System.State']
But the ones below will not:
query.fields.System.State
query[fields].System.State
This happens because, in the last two ways, JavaScript will think you are trying to access the State property of the query.fields.System object (which does not exist).
The same applies for objects that have a property whose name contain spaces. Accessing them as object['my property'] will work, but using the dot notation with object.my property will not.
Additional questions regarding this can be seen here:
Dot Notation and Square Bracket Notation in JavaScript
JavaScript property access: dot notation vs. brackets?
What is reason of using ' [ ] ' notation to access javascript object members instead of dot notation?
Try this:
var $list = query.fields["System.WorkItemType"];
JavaScript will interpret the System and WorkItemType as nested properties because of the dot.
Access to json elements is very easy:
1º Create a new var to transform the json data to a new object. Really json has the javascript object format.
var data = '{ "count": 15, "value": [ {"id": 284, "rev": 1, "fields": {"System.WorkItemType": "User Story", "System.State": "New", "System.Reason": "New", "System.CreatedDate": "2016-06-23T14:31:37.567Z", }, ...(some code below) '
var json = JSON.parse(data);
2º Access to a specific element of the object via “.” or “[]”:
Dot notation:
var json.value[n].fields['System.State'];
Note that you can use dot notation with System.State key.
[] notation:
var json['value'][n]['fields']['System.State'];
being n the index to access to a specific element of your object array
Related
HI i have a problem in accessing the data in the object, my object is
profile: Object {
"-L6LmpGWAClPdVK-cqvh": Object {
"first_name": "Mithun",
"isActive": true,
"isPrimary": true,
"last_name": "N",
"phoneNumber": "123454649",
"title": "Manager",
"uid": "Vz0pWQV3UxeCbGCbaf7ld4kaNRE3",
},
"active": true,
"businessCategory": "Retail",
"companyName": "Test"
}
Now my question is :
How to access -L6LmpGWAClPdVK-cqvh values, this -L6LmpGWAClPdVK-cqvh is dynamically generated randomly key.
i can get the value of this.props.profile.email
similarly how to get the this.props.profile.-L6LmpGWAClPdVK-cqvh.first_name (Currently it says undefined)
Please help!!!
In JavaScript there are two ways to access properties in objects. Dot notation object.property and square bracket notation object['property']. Both of these work if you know the name of the property. If you have a variable that stores the name of the property or your property contains characters that are invalid for properties then you can only use the square notation.
var key = '-L6LmpGWAClPdVK-cqvh';
var value = object[key];
So in your case you would have to use this.props.profile['-L6LmpGWAClPdVK-cqvh'].first_name. The - in your random name cannot be used as a raw key, has to be a string.
The JS parser will think you are doing this.props.profile. - L6LmpGWAClPdVK - cqvh.first_name. Spaces are added for clarity.
The key in this case contains the character "-" which is preventing you from accessing through object.(dot) so instead you have to use object['string']
We can able to iterate the object. Keys must be strings, and values must be a valid JSON data type (string, number, object, array, boolean or null). On iterating the object will return the keys that the object has. You can access the object values by using dot (.) notation and also by using bracket ([]) notation
for (var data in profile) {
if (data.hasOwnProperty(propName)) { //eg: propName which is first_name
var propValue = data[propName];
// do something with each element here
}
}
I have a very simple array (please focus on the object with "points.bean.pointsBase" as key):
var mydata =
{"list":
[
{"points.bean.pointsBase":
[
{"time": 2000, "caption":"caption text", duration: 5000},
{"time": 6000, "caption":"caption text", duration: 3000}
]
}
]
};
// Usually we make smth like this to get the value:
var smth = mydata.list[0].points.bean.pointsBase[0].time;
alert(smth); // should display 2000
But, unfortunately, it displays nothing. When I change "points.bean.pointsBase" to something without dots in its name - everything works.
However, I can't change this name to anything else without dots, but I need to get a value? Is there any options to get it?
What you want is:
var smth = mydata.list[0]["points.bean.pointsBase"][0].time;
In JavaScript, any field you can access using the . operator, you can access using [] with a string version of the field name.
in javascript, object properties can be accessed with . operator or with associative array indexing using []. ie. object.property is equivalent to object["property"]
this should do the trick
var smth = mydata.list[0]["points.bean.pointsBase"][0].time;
Try ["points.bean.pointsBase"]
If json object key/name contains dot......! like
var myJson = {"my.name":"vikas","my.age":27}
Than you can access like
myJson["my.name"]
myJson["my.age"]
This may be a very simple question but I really can't seem to make it work.
I have several JSON lines and a notes array.
Using notes.push(JSONline) I am saving one JSON line per array position, I assume, so in the following manner:
//notes[1]
{"id":"26","valuee":"20","datee":"2016-04-05T15:15:45.184+0100","id2":51}
//notes[2]
{"id":"27","valuee":"134","datee":"2016-04-05T15:15:47.238+0100","id2":53}
//notes[3]
{"id":"26","valuee":"20","datee":"2016-04-05T15:15:45.184+0100","id2":52}
Here is my problem: I want to print one specific attribute, for example id from one specific JSON line in the array. How can I do this?
When I do console.log(notes) it prints all the JSON lines just as expected. But if I do console.log(notes[1]) it prints the first character of the JSON line in that position, not the whole line.
Similarly console.log(notes[1].id) does not print the id from the first JSON line, in fact it prints 'undefined'.
What am I doing wrong?
Thank you so much.
I'd recommend that you parse all the json when you are pushing to notes, like:
notes.push(JSON.parse(JSONLine))
If you are somehow attached to having json strings in an array instead of objects, which I wouldn't recommend, you could always just parse once you have the jsonLine id
JSON.parse(notes[id]).id
Basically, you want to use JSON.parse for either solution and I'd strongly recommend converting them to objects once at the beginning.
You need to remember that JSON is the string representation of a JS object. JS strings have similar index accessor methods to arrays which is why you can write console.log(notes[0]) and get back the first letter.
JavaScript doesn't allow you to access the string using object notation, however, so console.log(notes[0].id) will not work and the reason you get undefined.
To access the data in the string using this method you need to parse the string to an object first.
var notes = ['{"id":"26","valuee":"20","datee":"2016-04-05T15:15:45.184+0100","id2":51}'];
var note0 = JSON.parse(notes[0]);
var id = note0.id;
DEMO
This leaves the question of why you have an array of JSON strings. While it's not weird or unusual, it might not be the most optimum solution. Instead you could build an array of objects and then stringify the whole data structure to keep it manageable.
var obj0 = {
"id": "26",
"valuee": "20",
"datee": "2016-04-05T15:15:45.184+0100",
id2: 51
};
var obj1 = {
"id": "27",
"valuee": "134",
"datee": "2016-04-05T15:15:47.238+0100",
"id2": 53
}
var arr = [obj0, obj1];
var json = JSON.stringify(arr);
OUTPUT
[
{
"id": "26",
"valuee": "20",
"datee": "2016-04-05T15:15:45.184+0100",
"id2": 51
},
{
"id": "27",
"valuee": "134",
"datee": "2016-04-05T15:15:47.238+0100",
"id2": 53
}
]
You can then parse the JSON back to an array and access it like before:
var notes = JSON.parse(json);
notes[0].id // 26
That's because you have {"id": "value"... as a string in your key value pairs. "id" is a string so you can't reference it like a property. 1. use
var notes = JSON.parse(notes);
as mentioned in the comments by The alpha
or remove the quotes try
{id:"26", ...}
that's why notes[i].id is returning undefined
This question already has answers here:
What is the difference between JSON and Object Literal Notation?
(10 answers)
Closed 7 years ago.
i cant see the difference between:
self.todos = [{
"todo": {
"title": "title",
"content": "lorem"
}
}, {
"todo": {
"title": "title",
"content": "lorem"
}
}];
and
self.todos = [{
todo: {
title: "title",
content: "lorem"
}
}, {
todo: {
title: "title",
content: "lorem"
}
}];
both work in my code but only the first veryfies JSON (online JOSON veryfier). Is there a preference what to use.
thanks a lot
The strict difference between JSON and JavaScript literals is only how you use it.
JSON is a text format to represent data. JavaScript literals is a part of JavaScript code.
You can't use JSON in JavaScript code, because then it's by definition not JSON any more, it's JavaScript. You can take JSON and use as JavaScript code, however. You can also have JSON inside a string in JavaScript.
JSON syntax is a subset of JavaScript literals syntax, so you can take any JSON and use as JavaScript, but you can't take any JavaScript literal and use as JSON.
This is an example of JSON:
[{
"todo": {
"title": "title",
"content": "lorem"
}
}]
You can use that as JavaScript:
var arr = [{
"todo": {
"title": "title",
"content": "lorem"
}
}];
You can also have the JSON as a string and parse it to a JavaScript value:
var json = '[{ "todo": { "title": "title", "content": "lorem" } ]';
var arr = JSON.parse(json);
Note that parsing JSON does't use the JSON as JavaScript, it reads the JSON and creates JavaScript values that corresponds to it. (Before JSON parsing was available the eval function was used to parse JSON, and that would actually use the JSON as JavaScript. JSONP requests still use JSON as JavaScript, as it loads the data using a script tag.)
JavaScript is less strict and doesn't require delimiters for object property names that can be used as identifier. Also, you can use expressions when creating JavaScript literals:
var arr = [{
todo: {
title: document.title,
content: "lo" + "rem"
}
}];
If you take that JavaScript literal and try to use as JSON, the syntax is wrong.
If you're writing JSON, you must conform to the rules for JSON, which include the fact that the property names must be in double quotes. (And that strings must be in double, not single quotes, and there's no undefined or functions, and various other things...)
What you're writing clearly isn't JSON, however, it's JavaScript code; I can tell from the self.todos = part. So you can use no quotes, single quotes, or double quotes on the property names; it's up to you. There are some property names where you need quotes, for instance when the property name has a space:
var o = {
"I have a space": 42
};
The key distinction is that JavaScript source code is source code, and JSON is a textual notation for data exchange which is a simplified version of one small part of JavaScript source code. When you're dealing with JavaScript source code, you're not dealing with JSON, unless you're dealing with strings (e.g., a string containing JSON, which you might parse or send to a server or similar).
I am trying to get data from an object. I have tried to get the data as a.doc._id as given below.
function ab(data){alert("content is "+data.doc.id);}
You probably need to access the property using the square bracket notation. Try -
alert("sdf" + data["doc._id"]);
"doc" is not an object, as shown in the inspector, you should rename the property name to something like doc-title instead.
Otherwise, you should create the object something like this
var data = {
"act" : "",
"doc": {
"_id" : "9",
"title": "fghfgh"
}
};