Get value from JSON data [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have this JSON data with me and I want to get the value of slug from every child.
The main problem is I don't know how much children will be generated after every time I got new data. In short generation of a child inside the child is dynamic that is not fixed.
So, How can I get the value of slug from every child that is present in JSON data?
Here I write one JSON data:
[
{
"id": 11,
"title": "Bottle",
"__domenu_params": {},
"href": "www.products.com",
"target": "_blank",
"slug": "/undefined"
},
{
"id": 10,
"title": "Pencils",
"__domenu_params": {},
"slug": "/Pencils"
},
{
"id": 9,
"title": "Stationary",
"__domenu_params": {},
"slug": "/Stationary"
},
{
"id": 8,
"title": "Pen",
"__domenu_params": {},
"slug": "/Pen"
},
{
"id": 7,
"title": "Cable",
"__domenu_params": {},
"slug": "/Cable"
},
{
"id": 5,
"title": "Electronics",
"__domenu_params": {},
"slug": "/Electronics",
"children": [
{
"id": 4,
"title": "Charger",
"__domenu_params": {},
"slug": "/Charger"
},
{
"id": 3,
"title": "Laptop",
"__domenu_params": {},
"slug": "/Laptop"
},
{
"id": 2,
"title": "Mobile",
"__domenu_params": {},
"slug": "/Mobile",
"href": "www.electronics.com",
"target": "_blank",
"children": [
{
"id": 6,
"title": "Pendrive",
"__domenu_params": {},
"slug": "/Pendrive",
"href": "www.pendrive.com",
"target": "_self"
}
]
}
]
}
]
I tried this code and get the value of slug from this JSON only. What should I do to get for every possible JSON data?
let data = [{"id":11,"title":"Bottle","__domenu_params":{},"href":"www.products.com","target":"_blank","slug":"/undefined"},{"id":10,"title":"Pencils","__domenu_params":{},"slug":"/Pencils"},{"id":9,"title":"Stationary","__domenu_params":{},"slug":"/Stationary"},{"id":8,"title":"Pen","__domenu_params":{},"slug":"/Pen"},{"id":7,"title":"Cable","__domenu_params":{},"slug":"/Cable"},{"id":5,"title":"Electronics","__domenu_params":{},"slug":"/Electronics","children":[{"id":4,"title":"Charger","__domenu_params":{},"slug":"/Charger"},{"id":3,"title":"Laptop","__domenu_params":{},"slug":"/Laptop"},{"id":2,"title":"Mobile","__domenu_params":{},"slug":"/Mobile","href":"www.electronics.com","target":"_blank","children":[{"id":6,"title":"Pendrive","__domenu_params":{},"slug":"/Pendrive","href":"www.pendrive.com","target":"_self"}]}]}]
for (let i = 0; i< data.length ; i++) {
// console.log(data[i]["children"])
if (data[i]["children"]) {
console.log("inside")
for (let j = 0; j < data[i]["children"].length; j++) {
// console.log(data[i]["children"][j])
if (data[i]["children"][j]["children"]) {
console.log(data[i]["children"][j]["children"])
}
}
}
}

You can use Recursion to parse this data easily:
let data = [{"id":11,"title":"Bottle","__domenu_params":{},"href":"www.products.com","target":"_blank","slug":"/undefined"},{"id":10,"title":"Pencils","__domenu_params":{},"slug":"/Pencils"},{"id":9,"title":"Stationary","__domenu_params":{},"slug":"/Stationary"},{"id":8,"title":"Pen","__domenu_params":{},"slug":"/Pen"},{"id":7,"title":"Cable","__domenu_params":{},"slug":"/Cable"},{"id":5,"title":"Electronics","__domenu_params":{},"slug":"/Electronics","children":[{"id":4,"title":"Charger","__domenu_params":{},"slug":"/Charger"},{"id":3,"title":"Laptop","__domenu_params":{},"slug":"/Laptop"},{"id":2,"title":"Mobile","__domenu_params":{},"slug":"/Mobile","href":"www.electronics.com","target":"_blank","children":[{"id":6,"title":"Pendrive","__domenu_params":{},"slug":"/Pendrive","href":"www.pendrive.com","target":"_self"}]}]}]
function getAllSlugs(categories) {
// For each category...
return categories.reduce((slugList, category) => {
// add the slug for the particular category...
slugList.push(category.slug);
// and, check if the category has children...
if (category.children && category.children.length) {
// if children are there, call the same function with the
// children and add the slugs of children
slugList = slugList.concat(getAllSlugs(category.children));
}
return slugList;
}, []);
}
// Call the function
getAllSlugs(data);
Output:
[ '/undefined',
'/Pencils',
'/Stationary',
'/Pen',
'/Cable',
'/Electronics',
'/Charger',
'/Laptop',
'/Mobile',
'/Pendrive' ]
Hope this helps!

Related

how i get title from following response [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
How i can get title or body from the following json response?
{
"message": "All Books",
"data": {
"current_page": 1,
"data": [
{
"id": 2,
"title": "The Quran",
"slug": "the-quran",
"body": "The Holy Quran",
"book": "/storage/books/1602685137.pdf",
"cover": "/storage/covers/1602685137.jpg",
"os": "both",
"price_ios": 0,
"price_android": 0,
"created_at": "2020-10-14T14:18:57.000000Z",
"updated_at": "2020-10-14T14:18:57.000000Z"
}
],
"first_page_url": "https://book.test/api/v1/books?page=1",
"from": 1,
"last_page": 1,
"last_page_url": "https://book.test/api/v1/books?page=1",
"links": [
{
"url": null,
"label": "Previous",
"active": false
},
{
"url": "https://book.test/api/v1/books?page=1",
"label": 1,
"active": true
},
{
"url": null,
"label": "Next",
"active": false
}
],
"next_page_url": null,
"path": "https://book.test/api/v1/books",
"per_page": 15,
"prev_page_url": null,
"to": 1,
"total": 1
}
}
Say the json is stored in a variable res.
Since the second data object is stored as an array [].
title = res['data']['data'][0]['title'];
body = res['data']['data'][0]['body'];
If you find a case where the array has more than one object, then you will have to change 0 to the index of the object in the array.
Reference: www.json.org
Assuming your JSON is assigned to a variable called response you can access the body with:
let body = response.data.data[0].body
And the title with
let title = response.data.data[0].title
In case you want to loop over the data array in order to get a value for all entries (e.g. title), try this:
let titles = response.data.data.forEach(entry => console.log(entry.title));

process array of objects [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have this code,
"data": [
{
"pid": 1,
"status": "done",
"title": "a"
},
{
"pid": 1,
"status": "pending",
"title": "a"
},
{
"pid": 1,
"status": "pending",
"title": "21"
},
{
"pid": 2,
"status": "pending",
"title": "c"
}
]
I am trying to process it like this
"data": [
{
"pid": 1,
"done": 1,
"pending":2
},
{
"pid": 2,
"done": 0,
"pending":1
}
]
I have tried much to produce my desired results but no luck, now i m posting here to get some help.
thanks
You should be able to use Array.reduce for this purpose.
We create a map, keyed by pid then add 1 for each done or pending object.
Object.values will then turn this map into an array again.
I hope this helps you!
data = [
{
"pid": 1,
"status": "done",
"title": "a"
},
{
"pid": 1,
"status": "pending",
"title": "a"
},
{
"pid": 1,
"status": "pending",
"title": "21"
},
{
"pid": 2,
"status": "pending",
"title": "c"
}
]
let result = Object.values(data.reduce( (map, d) => {
if (!map[d.pid]) map[d.pid] = { pid: d.pid, done: 0, pending: 0 };
if (d.status === "done") map[d.pid].done++;
if (d.status === "pending") map[d.pid].pending++;
return map;
}, {} ));
console.log("Result:", result);

Postman - How to count occurrences of a specific object in a JSON response

I am new to JSON and Postman. I believe I'm trying to do something very simple.
I have created a GET request which will get a JSON response like the one below.
In the example below I want to get the count of All "IsArchived" attributes in the response;
The number of those attributes will vary from response to response.
How can I do it? Thanks in advance
{
"Id": 1328,
"Name": "AAA Test",
"Owner": {
"Id": 208,
"Name": "The Boss"
},
"FieldGroups": [
{
"Id": "c81376f0-6ac3-4028-8d61-76a0f815dbf8",
"Name": "General",
"FieldDefinitions": [
{
"Id": 1,
"DisplayName": "Product Name",
"IsArchived": false
},
{
"Id": 2,
"DisplayName": "Short Description",
"IsArchived": false
},
{
"Id": 33,
"DisplayName": "Long Description",
"IsArchived": false
},
]
},
{
"Id": "5ed8746b-0fa8-4022-8216-ad3af17db91f",
"Name": "Somethingelse",
"FieldDefinitions": [
{
"Id": 123,
"DisplayName": "Attribution",
"IsArchived": false
},
{
"Id": 1584,
"DisplayName": "FC1",
"IsArchived": false
},
{
"Id": 623,
"DisplayName": "Sizes",
"IsArchived": false,
"Owner": {
"Id": 208,
"Name": "The Boss"
},
"Unit": "",
"Options": [
{
"Id": 1,
"Value": "XS"
},
{
"Id": 2,
"Value": "S"
},
{
"Id": 3,
"Value": "M"
}
]
}
]
}
],
"IsArchived": false
"Version": 1
}
It is a rather specific solution but I hope it helps. The description is added as comments:
// Convert the response body to a JSON object
var jsonData = pm.response.json()
// Create a count variable which will be increased by 1 everytime IsArchived occurs
var count = 0;
function countIsArchived() {
// Loop through the FieldGroupsArray
_.each(jsonData.FieldGroups, (fieldGroupsArray) => {
// Loop through the FieldDefinitionsArray
_.each(fieldGroupsArray.FieldDefinitions, (fieldDefinitionsArray) => {
// Check if IsArchived exists
if(fieldDefinitionsArray.IsArchived) {
// Increase count by 1
count++;
}
});
});
// IF you want it:
// Check if IsArchived exists on the top level of the JSON response and increase count
if(jsonData.IsArchived) {
count++;
}
// IF you want it:
// Create a Postman environment variable and assign the value of count to it
pm.environment.set("count", count);
}
Additional info:
The , after the following object is not needed. It invalidates the JSON:
{
"Id": 33,
"DisplayName": "Long Description",
"IsArchived": false
}, <--

How to find the number of nodes returned in an API response using postman?

Suppose the following is the API response:
{
"content":
[
{
"id": 90008,
"capacity": 2,
"manufacturer": "NISSAN",
"model": "Sunny",
"comment": "Nice Compact car.",
"features": {
"high_grade": false,
"normal_grade": true
},
"images": [
{
"type": "OUTSIDE",
"url": "http://some-image-1.jpg"
},
{
"type": "INSIDE",
"url": "http://some-image-2.jpg"
}
],
"links": []
},
{
"id": 90009,
"capacity": 7,
"manufacturer": "Audi",
"model": "Q7",
"comment": "Very good leg space!",
"features": {
"high_grade": true,
"normal_grade": false
},
"images": [
{
"type": "OUTSIDE",
"url": "http://some-image-1.jpg"
},
{
"type": "INSIDE",
"url": "http://some-image-2.jpg"
}
],
"links": []
}
],
"page": {
"size": 20,
"total_elements": 2,
"total_pages": 1,
"number": 0
}
}
Now in postman, how will I find out that the total number of parent/main nodes returned in content is 8 which is as follows:
id
capacity
manufacturer
model
comment
features
images
links
I tried with the following but it failed:
pm.test("Check total no. of nodes in all content is 8", () => {
for (i = 0; i < jsonData.content.length; i++) {
pm.expect(Object.keys(jsonData.content[i]).length).to.equal(8);
}
});
Your code is just missing:
var jsonData = pm.response.json()
Which the test would have told you when it was ran and gave you the Check total no. of nodes in all content is 8 | ReferenceError: jsonData is not defined message.
So it should look something like this:
pm.test("Check total no. of nodes in all content is 8", () => {
var jsonData = pm.response.json()
for (i = 0; i < jsonData.content.length; i++) {
console.log(Object.keys(jsonData.content[i]))
pm.expect(Object.keys(jsonData.content[i]).length).to.equal(8);
}
});
You mentioned that The 0 indexed nodes, such as links, can be ignored but the way that you have your test and what you're checking for would include them anyway. They are also part of the list that you attached to the question.
I added the line console.log(Object.keys(jsonData.content[i])) to show you that in the Postman Console.

If an array has an attribute, find the value of another attribute of the same array? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
"dTableRowData": [
{
"id": "1",
"rowData": [
"tt",
"Sep13, 2010"
],
"action": [
{
"hrefvar": "aaa",
"label": "fff"
},
{
"hrefvar": "bbb",
"label": "Details"
},
{
"hrefvar": "ccc",
"label": "View"
}
]
}
]
Above is the array I have, and I need to find the value of "action" by taking the "id" (if action is present). Please help me achieve this using jQuery.
This question is closed
I think you need something like bellow. You have a JSON like bellow.
var data = {"dTableRowData": [
{
"id": "1",
"rowData": [
"tt",
"Sep13, 2010"
],
"action": [
{
"hrefvar": "aaa",
"label": "fff"
},
{
"hrefvar": "bbb",
"label": "Details"
},
{
"hrefvar": "ccc",
"label": "View"
}
]
}
]}
You want to get an action for every object in dTableRowData. I added curly braces to dTableRowData other wise it will throw error.
So this is what worked for me using Javascript.
var actions = data.dTableRowData.map(function (obj) {
// Get each object in data.dTableRowData and get action according to it's id from object
return obj.action[obj.id];
});
console.log(actions);
First of all it has got nothing to do with jQuery.
Second, its a syntax error.
You need to wrap this in { and } to make it valid.
You can use this tool to check the validity of your JSON.
Next, this is how you do it. I've validated the JSON and added dummy data so that there is one element that doesn't have action attribute.
var array ={
"dTableRowData": [
{
"id": "1",
"rowData": [
"tt",
"Sep13, 2010"
],
"action": [
{
"hrefvar": "aaa",
"label": "fff"
},
{
"hrefvar": "bbb",
"label": "Details"
},
{
"hrefvar": "ccc",
"label": "View"
}
]
},
{
"id": "3",
"rowData": [
"tt",
"Sep13, 2010"
],
"action": [
{
"hrefvar": "aaa",
"label": "fff"
},
{
"hrefvar": "bbb",
"label": "Details"
},
{
"hrefvar": "ccc",
"label": "View"
}
]
},
{
"id": "2",
"rowData": [
"tt",
"Sep13, 2010"
]
}
]
};
This is a function that returns all the IDs that have actions
function getRequiredIDs(myArray){
var ids = [];
for (var tableRowData in myArray.dTableRowData){
var elements = myArray.dTableRowData[tableRowData];
if(elements.action!=null){
ids.push(elements.id);
}
}
return ids;
}
And this is how you use it
var ids = getRequiredIDs(array);
var result = ""
for(var i=0;i<ids.length;i++){
result+=ids[i]+" ";
}
alert("IDs that have actions are - "+result);
Here is the fiddle
EDIT:
If you want to get actions for specific id, you need to change the code a bit like following.
function getRequiredActions(_id,myArray){
for (var tableRowData in myArray.dTableRowData){
var elements = myArray.dTableRowData[tableRowData];
if(elements.id == _id){
if(elements.action != null){
return elements.action;
} else {
return false;
}
}
}
}
And this is how you use it.
var actions = getRequiredActions("1",array);
console.log(actions);
Final fiddle

Categories

Resources