How can I get access to multiple values of nested JSON object? - json

I try to access to my data json file:
[{"id":1,"name":"Maria","project":[{"id":5,"name":"Animals"},{"id":6,"name":"Cats"}]}
This is my approach:
data[0].name;
But like this I get only the result:
Animals
But I would need the result:
Animals, Cats

You are accessing only the name property of 0th index of project array.
To access all object at a time you need to loop over the array.
You can use Array.map for this.
var data = [{"id":1,"name":"Maria","project":[{"id":5,"name":"Animals"},{"id":6,"name":"Cats"}]}]
var out = data[0].project.map(project => project.name).toString()
console.log(out)

If that's your actual data object, then data[0].name would give you "Maria". If I'm reading this right, though, you want to get all the names from the project array. You can use Array.map to do it fairly easily. Note the use of an ES6 arrow function to quickly and easily take in the object and return its name.
var bigObject = [{"id":1,"name":"Maria","project":[{"id":5,"name":"Animals"},{"id":6,"name":"Cats"}]}];
var smallObject = [{"id":5,"name":"Animals"},{"id":6,"name":"Cats"}];
console.log("Getting the names from the full array/data structure: "+bigObject[0].project.map(obj => obj.name))
console.log("Getting the names from just the project array: "+smallObject.map(obj => obj.name))
EDIT: As per your comment on the other answer, you said you needed to use the solution in this function:
"render": function (data, type, row) {if(Array.isArray(data)){return data.name;}}
To achieve this, it looks like you should use my bottom solution of the first snippet like so:
var data = [{"id":5,"name":"Animals"},{"id":6,"name":"Cats"}];
function render(data, type, row){
if(Array.isArray(data)){
return data.map(obj => obj.name);
}
};
console.log("Render returns \""+render(data)+"\" as an array.");

Related

POSTMAN - Save a property value from a JSON response

I am new to both JSON and Postman(as of yesterday).
I'm trying to do something very simple, I've created a GET request which pulls in a list of forms in a JSON response. I want to take this response and get the first "id" token and place it in a variable.
I am using a global variable but would like to use a collection variable if possible. Either way here is what I am doing.
I've tried several things, most recently this:
var jsonData = JSON.parse(responseBody);
postman.setGlobalVariable("id", jsonData.args.id);
As well as this:
pm.test("GetId", function () {
var jsonData = pm.response.json();
pm.globals.set("id", jsonData.id);
});
Response code looks like this:
{
"forms":[
{
"id":"3197239",
"created":"2018-09-18 11:37:39",
"db":"1",
"deleted":"0",
"folder":"151801",
"language":"en",
"name":"Contact Us",
"num_columns":"2",
"submissions":"0",
"submissions_unread":"0",
"updated":"2018-09-18 12:02:13",
"viewkey":"xxxxxx",
"views":"1",
"submissions_today":0,
"url":"https://xxx",
"data_url":"",
"summary_url":"",
"rss_url":"",
"encrypted":false,
"thumbnail_url":null,
"submit_button_title":"Submit Form",
"inactive":false,
"timezone":"US/Eastern",
"permissions":150
},
{
"id":"3197245",
"created":"2018-09-18 11:42:02",
"db":"1",
"deleted":"0",
"folder":"151801",
"language":"en",
"name":"Football Draft",
"num_columns":"1",
"submissions":"0",
"submissions_unread":"0",
"updated":"2018-09-18 12:11:54",
"viewkey":"xxxxxx",
"views":"1",
"submissions_today":0,
"url":"https://xxxxxxxxx",
"data_url":"",
"summary_url":"",
"rss_url":"",
"encrypted":false,
"thumbnail_url":null,
"submit_button_title":"Submit Form",
"inactive":false,
"timezone":"US/Eastern",
"permissions":150
}
]
}
This would get the first id:
pm.globals.set('firstId', _.first(pm.response.json().forms).id)
That would get the first in the array each time so it would set a different variable it that response changed.
The test that you created was nearly there but the reference needed to go down a level into the forms array:
pm.test("GetId", function () {
var jsonData = pm.response.json()
pm.expect(jsonData.forms[0].id).to.equal("3197239")
pm.globals.set("id", jsonData.forms[0].id)
})
The [0]is referencing the first id in the first object within the array. For example [1] would get the second one and so on.
You currently cannot set a collection level variable using the pm.* API - These can only be added manually and referenced using the pm.variables.get('var_name') syntax.
Edit:
In the new versions of the desktop app you can set variables at the Collection level using pm.collectionVariables.set().
Based on the name or any other attribute if you want to set the id as a global variable then this is the way.
for(var i=0; i<jsonData.forms.length; i++)
{
if (jsonData.forms[i].name==="Contact Us")
{
pm.environment.set("id", jsonData.forms[i].id);
}
}

Vuejs changes order of json_encoded array, when decodes it back from props in vuejs component

Php:
$json_string = "{
"26":{"blabla":123,"group_id":1,"from":"27.08.2018","to":"02.09.2018"},
"25":{"blabla":124,"group_id":1,"from":"20.08.2018","to":"26.08.2018"},
"24":{"blabla":125,"group_id":1,"from":"20.08.2018","to":"26.08.2018"}
}"
my.blade.php template:
<my-component :records={{ $json_string }}></my-component>
MyComponent.vue:
export default {
props: ['records'],
...
mounted: function () {
console.log(this.records);
}
Output is:
{__ob__: Observer}
24:(...)
25:(...)
26:(...)
And when I use v-for, records in my table in wrong order (like in console.log output).
What I am doing wrong?
EDIT:
I figured out 1 thing:
When I do json_encode on collection where indexes are from 0 till x, than json string is: [{some data}, {some data}]
But if I do ->get()->keyBy('id') (laravel) and than json_encode, json string is:
{ "26":{some data}, "25":{some data}, "24":{some data} }
Then how I understood, issue is in different outer brackets.
In Javascript keys of objects have no order. If you need a specific order then use arrays.
Here is documentation for keyBy Laravel method: https://laravel.com/docs/5.6/collections#method-keyby
I wanted to have ids for rows data to fast and easy access without iterating over all rows and check if there is somewhere key Id which is equals with my particular Id.
Solution: not to use keyBy method in Laravel and pass json string to Vue component like following [{some data}, {some data}] (as I described in my Question Edit section) - this will remain array order as it used to be.
I found this short and elegant way how to do this, instead of writing js function by myself:
Its find() method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
Example:
let row = records.find( record => record.id === idToFind );

JSON - look up values in array

With the following json
{
"Count":0,
"Message":{
"AppId":0
},
"Data":"[{\"application_name\": \"Grand Central\",\"feature_name\": \"1 Click Fix\",\"access_type_id\": 2,\"member_name\": \"GC_Remote_Support_Security\"},{\"application_name\": \"Grand Central\",\"feature_name\": \"Account Details\",\"access_type_id\": 2,\"member_name\": \"GC_Remote_Support_Security\"},{\"application_name\": \"Grand Central\",\"feature_name\": \"Account Summary\",\"access_type_id\": 2,\"member_name\": \"GC_Remote_Support_Security\"}]"
}
how do I go through the Data array, in the most succinct coding manner possible, to see if any feature_name matches a given string?
Since your JSON contains nested, quoted JSON, you will need nested deserializations using LINQ to JSON to parse your Data array. Having done so, you can use use SelectTokens to query with a JSONPath query to find nested properties named feature_name, then check their value:
var testString = "Account Summary";
var found = JToken.Parse(JObject.Parse(jsonString)["Data"].ToString()).SelectTokens("..feature_name").Any(t => (string)t == testString);
Debug.Assert(found == true); // No assert.
Update
If you want the all JObject with a "feature_name" property matching a given value, you can do:
var foundItems = JToken.Parse(JObject.Parse(jsonString)["Data"].ToString())
.SelectTokens("..feature_name")
.Where(t => (string)t == testString)
.Select(t => t.Ancestors().OfType<JObject>().First()) // Get the immediate parent JObject of the matching value
.ToList();

Filtering and rearranging model/content in Ember Controllers

Let's say I have a JSON array of data, something like:
[ {"name":"parijat","age":28},
{"name":"paul","age":28},
{"name":"steven","age"27},
...
]
that is part of my model, and this model is setup like this:
App.UserRoute = Ember.Route.extend({
model:function(){
return App.User.FIXTURES ; // defined above
}
});
I want to get the unique ages from this JSON array and display them in my template, so I reference the computed properties article and read up a little on how to enumerate Ember Enumerables, to eventually get this:
App.UserController = Ember.ArrayController.extend({
ages:function(){
var data = this.get('content');
var ages = data.filter(function(item){
return item.age;
});
}.property('content');
});
Now the above piece of code for controller is not correct but the problem is that it doesn't even go into data.filter() method if I add a console.log statements inside. IMO, it should typically be console logging as many times as there exist a App.Users.FIXTURE. I tried using property('content.#each') which did not work either. Nor did changing this.get('content') to this.get('content.#each') or this.get('content.#each').toArray() {spat an error}.
Not sure what to do here or what I am completely missing.
Filter is used for reducing the number of items, not for mapping.
You can use data.mapBy('age') to get an array of your ages:
ages:function(){
return this.get('content').mapBy('age');
}.property('content.#each')
or in your handlebars function you can just use the each helper:
{{#each item in controller}}
{{item.age}}
{{/each}}

SortOn an m-array of objects

Alright, so I have an m-array (Or an array of arrays in actionscript as it doesn't really have m-arrays) and each array in the superarray has a number of objects created at different times in it. I want to sort the superarray by in descending order of the value of the "time" paramater of the object at index 0 in each subarray.
I've tried
superarray.sortOn([0].time, Array.DESCENDING);
and
superarray.sortOn("0.time", Array.DESCENDING);
but this doesn't seem to work. Any suggestions? Will I just have to write my own sort function to do this? If so what's the best way to go about it?
Try using the Array.sort function passing a compare function. Something like this:
var superarray:Array = [
[{time:900}, {time:715}, {time:655}],
[{time:450}, {time:333}, {time:100}],
[{time:999}, {time:75}, {time:30}]
];
var sorted:Array = superarray.sort( function(A:Array,B:Array):int {
return ObjectUtil.numericCompare(A[0].time, B[0].time);
});