student123 student123 - 5 months ago 10
JSON Question

Accessing fields in .json file

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!

Answer

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: