How to read data from nested JSON structure in protractor - json

Below is my code and I want to extract data under "specs" part like description, status etc. however I'm getting undefined when I capture the data and print it in the console. I have tried
let web = JSON.parse(jsondata);
let TestSuite = web["suite1"]["description"]
and this is providing data in console however, when I use this,
let id = web["suite1"]["specs"]["id"]
its gives undefined. Please help!
{
"suite1": {
"id": "suite1",
"description": "Login",
"fullName": "Login",
"failedExpectations": [],
"status": "finished",
"specs": [
{
"id": "spec0",
"description": "Should able to login into the Distribution management Webpage",
"fullName": "Login Should able to login into the Distribution management Webpage",
"failedExpectations": [
{
"matcherName": "",
"message": "",
"stack": "",
"passed": false,
"expected": "",
"actual": ""
}
],
"passedExpectations": [],
"pendingReason": "",
"started": "2018-09-06T06:57:42.740Z",
"status": "failed",
"duration": "7 secs",
"stopped": "2018-09-06T06:57:49.255Z",
"browserLogs": []
}
]
} }

JSON.parse(JSON.stringify(json)).suite1.specs[0].id

specs contains an array of objects. First, you need to get the object from the array and then get a value of the object.
Try this:
let id = web["suite1"]["specs"][0]["id"]
OR
let id = web.suite1.specs[0].id
Hope this will work.

When you do ["suite1"]["specs"], you select array. You need an index, which is the 0-th one in this case.
You can check that by typing Object.prototype.toString.call( data["suite1"]["specs"]).
You can try with:
data["suite1"]["specs"][0]["id"]
Or use the object property notation
data["suite1"]["specs"][0].id

Related

Why is JSON being detected as empty?

So I have a JSON file I got from Postman which is returning as an empty object. This is how I'm reading it.
import regscooter from './json_files/reginald_griffin_scooter.json'
const scoot = regscooter;
const CustomerPage = () => {...}
reginald_griffin_scooter.json
{
"success": true,
"result": {
"id": "hhhhhhhhhh",
"model": "V1 Scooter",
"name": "hhhhhhhhhh",
"status": "active",
"availabilityStatus": "not-available",
"availabilityTrackingOn": true,
"serial": "hhhhhhhhhhhh",
"createdByUser": "hhhhhhhhK",
"createdByUsername": "hhhhhhhh",
"subAssets": [
"F0lOjWBAnG"
],
"parts": [
"hhhhhhhh"
],
"assignedCustomers": [
"hhhhhhhhh"
],
"createdAt": "2019-12-03T21:47:26.218Z",
"updatedAt": "2020-06-26T22:05:54.526Z",
"customFieldsAsset": [
{
"id": "hhhhhhh",
"name": "MAC",
"value": "hhhhhhhh",
"asset": "hhhhhhhhhh",
"user": "hhhhhhhhh",
"createdAt": "2019-12-03T21:47:26.342Z",
"updatedAt": "2019-12-11T16:29:24.732Z"
},
{
"id": "hhhhhhhh",
"name": "IMEI",
"value": "hhhhhhh",
"asset": "hhhhhhh",
"user": "hhhhhhhhhh",
"createdAt": "2019-12-03T21:47:26.342Z",
"updatedAt": "2019-12-11T16:29:24.834Z"
},
{
"id": "hhhhhhhhh",
"name": "Key Number",
"value": "NA",
"asset": "hhhhhhhhh",
"user": "hhhhhhhhhhh",
"createdAt": "2019-12-03T21:47:26.342Z",
"updatedAt": "2019-12-11T16:29:24.911Z"
}
]
}
}
The error is that "const scoot" is being shown as an empty object {}. I made sure to save a ton of times everywhere. I am able to read through the imported JSON file in other variables in similar ways, so I don't know why I can't parse this one. I just want to access the JSON object inside this. Also I omitted some information with hhhhh because of confidentiality.
EDIT: The code works, but it still has a red line beneath result when I do:
const scoot = regscooter.result.id;
It would be much more effective if you will provide an example in codesandbox or so.
However at first look it might be a parser issue ( maybe you are using Webpack with missing configuration for parsing files with json extension ), meaning we need more information to provide you with a full answer ( maybe solution ? ).
Have you tried to do the next:
const scoot = require('./json_files/reginald_griffin_scooter.json');

How to create a config file for a homebridge accessory

I have installed a plugin to control my Samsung TV (https://github.com/xeenon/homebridge-samsung-tv) via my Homebridge server, however the developer did not provide a config-sample.json, hence why I am trying to make my own. I am entirely new to coding so please tell me what I am doing wrong.
This is the part of my config file for that accessory as of now (I will add the ip adress and mac adress later).
{
"bridge": {
"name": "Homebridge",
"username": "",
"port": 4318,
"pin": "031-45-154"
},
"accessories": [{
"accessory": "samsungTv",
"name": "samsungTvAccessory",
"ip_address": "",
"macAddress": "",
"polling": "true",
"pollingInterval": "1"
}]
}
When I am trying to start Homebridge I get the error
TypeError: Cannot read property 'forEach' of undefined
at new SamsungTvAccessory (usr/local/lib/node_modules/homebridge-samsung-tv-controller/index.js:76:10
If I however change the config file to
{
"bridge": {
"name": "Homebridge",
"username": "",
"port": 4318,
"pin": "031-45-154"
},
"accessories": [{
"accessory": "samsungTv",
"name": "samsungTvAccessory",
"ip_address": "",
"macAddress": "",
"polling": "true",
"pollingInterval": "1",
"enabledInputs": "true"
}]
}
where I added
"enabledInputs": "true"
i get the error
TypeError: config.enabledInputs.forEach is not a function
at new SamsungTvAccessory (usr/local/lib/node_modules/homebridge-samsung-tv-controller/index.js:76:10
I would really appreciate any help!
Did you try valid JSON ? Would tell you are missing brackets around, also from first lines of source it looks like. It should work like this
objectVar = {
"accessory": "samsungTv",
"name": "samsungTvAccessory",
"ip_adress": "",
"macAddress": "",
"polling": "true",
"pollingInterval": "1"
}
Or like this in case it you are using string somewhere: "{\"accessory\":\"samsungTv\",\"name\":\"samsungTvAccessory\",\"ip_adress\":\"\",\"macAddress\":\"\",\"polling\":\"true\",\"pollingInterval\":\"1\"}"
And then there are methods JSON.stringify(objectVar [, null, indent]) or JSON.parse(string) to convert to string or back. Stringify has also optional parameters - first is a replacer function and second indent if you want it people friendly formatted.

How to retrieve only immediate child object from a JSON response using Spring 5

I have build a small microservice using SpringBoot2 and Spring 5 which has a REST service exposed (HTTP GET Method) and which internally consumes another REST GET service (third party API). Using Postman when I call my service (GET), then I get a JSON response but the problem is I get a complete whole object in response like below :-
[
{
"id": "1",
"name": "Open Catalogue",
"subcategories": [
{
"id": "106",
**"name": "Components",**
"subcategories": [
{
"id": "816",
"name": "Power Supplies",
"subcategories": [
{
"id": "814",
"name": "Rechargeable Batteries",
"subcategories": [],
"sample": {
"empty": true,
"lazy": false,
"async": false
}
},
{
"id": "829",
"name": "Battery Chargers",
"subcategories": [],
"samples": {
"empty": true,
"lazy": false,
"async": false
}
},
My service URL used in post man is like this :-
http://localhost:8080/test-search?searchKey=ball
So my requirement is whenever a user consume this service by a sub-category name then only that sub-category details along with its immediate child details should be returned and not the child of child.
Here searchKey in URL is nothing but a free text to search for a sub-category. For instance when I say :-
http://localhost:8080/test-search?searchKey=Components
then only below details should be returned like this :-
"id": "106",
"name": "Components",
"subcategories": [
{
"id": "816",
"name": "Power Supplies",
Response should not have sub-categories of Power Supplies i.e. "subcategories": [ "id": "814",
"name": "Rechargeable Batteries",
Is there any efficient way to do the filtering while preparing the JSON response or first fetch whole object and then start filtering?
Please advise, thank you

How to 'run' an IVR saved in JSON?

I am working on a IVR solution for small businesses in my local area but I am having trouble wrapping my head around how Node will handle menus. I could make a seperate Node server for each of my customers but I would like to have a single server that pulls each customer's IVR setup from a Mongo database or file when their number is called. I have an idea on how to save the menu structure in JSON but I am lost when it comes to turning that JSON into responses to <gather> inputs. I was thinking I could use a JSON structure like this in the DB (or maybe as a .json file on Amazon S3):
{
"menu": {
"id": 1,
"name": "Main",
"script": "Thank you for calling Local Company. To speak to sales press 1, ...",
"options": [
{
"name": "",
"action": "",
"value": "",
"next": ""
},
{
"name": "Sales",
"action": "dial",
"value": 12345678901,
"next": ""
},
{
"name": "Support",
"action": "dial",
"value": 12345678902,
"next": ""
},
{
"name": "Directions",
"action": "say",
"value": "Our offices are located at...",
"next": 1
},
{
"name": "Mailbox",
"action": "mailbox",
"value": "main",
"next": 1
}
]
}
}
Twilio developer evangelist here.
If you can return the JSON based on the number a user is dialling, then you could do something like this:
const Twilio = require('twilio');
app.post('/voice', (req, res) => {
const dialledNumber = req.body.To;
getIVRObjectFromPhoneNumber(dialledNumber, (IVRObject) => {
const twiml = Twilio.twiml.VoiceResponse();
if (typeof req.body.Digits !== 'undefined') {
// A user has pressed a digit, do the next thing!
const action = IVRObject.menu.options[req.body.Digits]
twiml[action.action](action.value);
} else {
// No digits yet, return the <Gather>
const gather = twiml.gather({
numDigits: 1
});
gather.say(IVRObject.script);
}
res.send(twiml.toString());
});
});
This doesn't quite use all of your object, I'm not sure what the values for next mean, but hopefully it's a start. The getIVRObjectFromPhoneNumber method is my made up, asynchronous method that returns a JavaScript object parsed from your example JSON above.
Let me know if this helps at all.

Parsing json in backbone

prodCollect.fetch({
success: function(collection){
console.log(prodCollect.models.length);
var a =prodCollect.models[1];
console.log(a.attributes);
var y=_(a.attributes).toArray();
console.log(y[0]);
}
});
In variable 'a', I'm getting a model and doing console(a.attributes), I'm getting this:
Object {[{"product_id":"2","product_name":"new product","short_description":"used for training of managers","full_description":"used for training of managers","price":"20000.00","acct_manager":"rahul raja","roles":"Manager,Manager","tags":"abc,def","skills":"abc,abc","clients":"accenture,accenture,Wipro,Google"}]: Object}
Now I am unable to access the properties like 'product_name' and 'price'. I tried converting a.attributes into an array and accessing y[0] but its undefined. 'a.attributes' is an object. So I am unable to access the properties.
I am sending this from server
[
"[{\"program_name\":\"training\",\"products\":\"new product,fdgf\",\"roles\":\"Manager,CEO,random\",\"tags\":\"abc,def\",\"skills\":\"abc,def\",\"clients\":\"accenture,wipro\"},{\"program_name\":\"New progs\",\"products\":\"fdgf,ILead\",\"roles\":\"CEO,Manager,random\",\"tags\":\"abc,def\",\"skills\":\"abc,def\",\"clients\":\"\"}]",
"[{\"product_id\":\"2\",\"product_name\":\"new product\",\"short_description\":\"used for training of managers\",\"full_description\":\"used for training of managers\",\"price\":\"20000.00\",\"acct_manager\":\"rahul raja\",\"roles\":\"Manager,Manager\",\"tags\":\"abc,def\",\"skills\":\"abc,abc\",\"clients\":\"accenture,accenture,Wipro,Google\"}]"
]
so variable 'a' contains the second array
I think that the problem came from the server, your log should be like :
{
"product_id": "2",
"product_name": "new product",
"short_description": "used for training of managers",
"full_description": "used for training of managers",
"price": "20000.00",
"acct_manager": "rahul raja",
"roles": "Manager,Manager",
"tags": "abc,def",
"skills": "abc,abc",
"clients": "accenture,accenture,Wipro,Google"
}
Here is an example that illustrate what I suspected your server doing.
So as I suspected, your problem came from the server. Your server response should be like that :
[
{
"product_id": "2",
"product_name": "new product",
...
},
{
"product_id": "2",
"product_name": "new product",
...
},
...
]