Ηow to extract particular data from JSON inside JSON object - javascript

A packet contains the data below but I need to extract the following part:
"data":"YOeNkAAg1wQAYjm/pg==
using JavaScript in node-red. How i can do this?
{
"payload": "lora/01-01-01-01-01-01-01-01/39-31-37-33-5b-37-67-19/packet_sent
{
\"appeui\":\"01-01-01-01-01-01-01-01\",
\"codr\":\"4/5\",
\"data\":\"YOeNkAAg1wQAYjm/pg==\",
\"datr\":\"SF7BW125\",
\"deveui\":\"39-31-37-33-5b-37-67-19\",
\"freq\":868.29999999999995,
\"gweui\":\"00-80-00-00-a0-00-24-6d\",
\"id\":0,
\"ipol\":true,
\"mhdr\":\"60e78d900020d704\",
\"mic\":\"6239bfa6\",
\"modu\":\"LORA\",
\"ncrc\":true,
\"opts\":\"\",
\"port\":0,
\"powe\":11,
\"rfch\":0,
\"seqn\":1239,
\"size\":13,
\"tmst\":3491353235,
\"twnd\":1
}",
"fromip": "127.0.0.1:35068",
"ip": "127.0.0.1",
"port": 35068,
"_msgid": "193b00a8.e6c4ff"
}

var src = {
"payload": "lora/01-01-01-01-01-01-01-01/39-31-37-33-5b-37-67-19/packet_sent {\"appeui\":\"01-01-01-01-01-01-01-01\",\"codr\":\"4/5\",\"data\":\"YOeNkAAg1wQAYjm/pg==\",\"datr\":\"SF7BW125\",\"deveui\":\"39-31-37-33-5b-37-67-19\",\"freq\":868.29999999999995,\"gweui\":\"00-80-00-00-a0-00-24-6d\",\"id\":0,\"ipol\":true,\"mhdr\":\"60e78d900020d704\",\"mic\":\"6239bfa6\",\"modu\":\"LORA\",\"ncrc\":true,\"opts\":\"\",\"port\":0,\"powe\":11,\"rfch\":0,\"seqn\":1239,\"size\":13,\"tmst\":3491353235,\"twnd\":1}",
"fromip": "127.0.0.1:35068",
"ip": "127.0.0.1",
"port": 35068,
"_msgid": "193b00a8.e6c4ff"
}
var payload = src.payload;
payload = JSON.parse(payload.substr(payload.indexOf('{')));
console.log(payload.data);
console.log('"data":"' + payload.data + '"');
var finalResult = {};
finalResult.data = payload.data;
console.log(JSON.stringify(finalResult));
And after removing this strange part JSON could look like this
{
"payload": {
"appeui": "01-01-01-01-01-01-01-01",
"codr": "4/5",
"data": "YOeNkAAg1wQAYjm/pg==",
"datr": "SF7BW125",
"deveui": "39-31-37-33-5b-37-67-19",
"freq": 868.3,
"gweui": "00-80-00-00-a0-00-24-6d",
"id": 0,
"ipol": true,
"mhdr": "60e78d900020d704",
"mic": "6239bfa6",
"modu": "LORA",
"ncrc": true,
"opts": "",
"port": 0,
"powe": 11,
"rfch": 0,
"seqn": 1239,
"size": 13,
"tmst": 3491353235,
"twnd": 1
},
"fromip": "127.0.0.1:35068",
"ip": "127.0.0.1",
"port": 35068,
"_msgid": "193b00a8.e6c4ff"
}

If the resualt always look like data...== you can search in the payload for the content between data and == with
var res = array.payload.substring(
response.payload.lastIndexOf("data") + -1,
response.payload.lastIndexOf("==") + 3
);
var response = {
"payload": "lora/01-01-01-01-01-01-01-01/39-31-37-33-5b-37-67-19/packet_sent {\"appeui\":\"01-01-01-01-01-01-01-01\",\"codr\":\"4/5\",\"data\":\"YOeNkAAg1wQAYjm/pg==\",\"datr\":\"SF7BW125\",\"deveui\":\"39-31-37-33-5b-37-67-19\",\"freq\":868.29999999999995,\"gweui\":\"00-80-00-00-a0-00-24-6d\",\"id\":0,\"ipol\":true,\"mhdr\":\"60e78d900020d704\",\"mic\":\"6239bfa6\",\"modu\":\"LORA\",\"ncrc\":true,\"opts\":\"\",\"port\":0,\"powe\":11,\"rfch\":0,\"seqn\":1239,\"size\":13,\"tmst\":3491353235,\"twnd\":1}",
"fromip": "127.0.0.1:35068",
"ip": "127.0.0.1",
"port": 35068,
"_msgid": "193b00a8.e6c4ff"
}
var res = response.payload.substring(
response.payload.lastIndexOf("data") + -1,
response.payload.lastIndexOf("==") + 3
);
console.log(res)

Related

Parsing JSON into Google spreadsheet (Apps Script)

I have a download in JSON format that I get through the API.
Example:
{
"Employees": [
{
"User": {
"UserId": "4d132227-ea5c-4e57-b105-2f8b97872545",
"Login": "test#gmail.com",
"FullName": {
"LastName": "Фамилия",
"FirstName": "Имя",
"MiddleName": "Отчество"
},
"IsRegistered": true
},
"Permissions": {
"UserDepartmentId": "b5072e57-1e96-490b-ae03-2fd52ef84a3a",
"IsAdministrator": false,
"DocumentAccessLevel": "SelectedDepartments",
"SelectedDepartmentIds": [
"b5072e57-1e96-490b-ae03-2fd52ef84a3a",
"cd2e04dc-8d3f-4d63-88fd-f900c496e146",
"36e4434b-519d-4e40-9253-3464c10ed83e"
],
"Actions": [
{
"Name": "CreateDocuments",
"IsAllowed": true
},
{
"Name": "DeleteRestoreDocuments",
"IsAllowed": true
},
{
"Name": "SignDocuments",
"IsAllowed": true
},
{
"Name": "AddResolutions",
"IsAllowed": true
},
{
"Name": "RequestResolutions",
"IsAllowed": true
},
{
"Name": "ManageCounteragents",
"IsAllowed": false
}
],
"AuthorizationPermission": {
"IsBlocked": false
}
},
"Position": "Специалист по снабжению",
"CanBeInvitedForChat": true,
"CreationTimestamp": {
"Ticks": 637284074150000000
}
}
],
"TotalCount": 214
}
An example of what should happen:
enter image description here
The ratio of the JSON list of employees with columns in the table:
A: "User": {"UserId"} - Employee ID
B: "User": {""FullName""} - FULL NAME
C: "Position" - Position
D: "User": {"Login"} - Mail
E: "User": {"IsRegistered"} - Login activated?
F: "Permissions": {"IsAdministrator"} - Administrator?
G: "Permissions": {"Actions": [{"Name": "SignDocuments","isAllowed": true} - Can sign documents
H: "Permissions": {"Actions": [{"Name": "AddResolutions","isAllowed": true} - Can coordinate documents
I: "Permissions": {"Actions": [{"Name": "RequestResolutions","isAllowed": true} - Can request document approval
J: "Permissions": {"Actions": [{"Name": "CreateDocuments","isAllowed": true} - Can create documents and work with drafts
K: "Permissions": {"Actions": [{"Name": "DeleteRestoreDocuments","isAllowed": true} - Can delete documents and drafts, restore documents
L: "Permissions": {"Actions": [{"Name": "ManageCounteragents","isAllowed": true} - Can work with a list of counterparties
How can I convert JSON to a Google spreadsheet for 300+ rows? At the moment I only have a request to the API. The response is JSON. What are my next steps?
function GetEmployees(){
var DdocAuthKey = GetAuthToken()
for (let i = 0; i < boxId.length; i++) {
let url = `https://diadoc-api.kontur.ru/GetEmployees?boxId=`+ boxId[i]
let options =
{
method: "GET",
contentType: 'application/json',
headers: {authorization: "DiadocAuth ddauth_api_client_id=" + DdocAPIkey + `,ddauth_token=` + DdocAuthKey}
}
var json = UrlFetchApp.fetch(url, options)
var obj = JSON.parse(json)
printValues(obj);enter code here
}
}
function printValues(obj) {
for(var k in obj) {
if(obj[k] instanceof Object) {
printValues(obj[k]);
} else {
return obj[k] + "<br>"
}
}
}
This is the final version of the code. I hope this will help developers on JS and Apps Script when working with the Diadoc API.
Due to the fact that I have 3 organizations, I need to do an additional cycle:
for (let i = 0; i < boxId.length; i++)
If necessary, this cycle can be removed.
function GetEmployees() {
clearOrgSheets()
var DdocAuthKey = GetAuthToken()
let options =
{
method: "GET",
contentType: 'application/json',
headers: {authorization: "DiadocAuth ddauth_api_client_id=" + DdocAPIkey + `,ddauth_token=` + DdocAuthKey}
}
for (let i = 0; i < boxId.length; i++) {
let sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SheetNames[i])
let pageNum = 1
do {
let url = `https://diadoc-api.kontur.ru/GetEmployees?boxId=`+ boxId[i] + `&page=` + pageNum + `&count=50`
pageNum++
var obj = JSON.parse(UrlFetchApp.fetch(url, options))
var table = []; // it will be the 2d array
for (var employee of obj.Employees) {
var {LastName, FirstName, MiddleName} = employee.User.FullName;
var name = [LastName, FirstName, MiddleName].join(' ').trim();
var actions = {};
employee.Permissions.Actions.forEach(a => actions[a.Name] = a.IsAllowed);
var row =
[
employee.User.UserId,
name,
employee.Position,
employee.User.Login,
employee.User.IsRegistered,
employee.Permissions.IsAdministrator,
actions.SignDocuments, // Can sign documents
actions.AddResolutions, // Can coordinate documents
actions.RequestResolutions, // Can request document approval
actions.CreateDocuments, // Can create documents and work with drafts
actions.DeleteRestoreDocuments, // Can delete documents and drafts, restore documents
actions.ManageCounteragents, // Can work with a list of counterparties
];
table.push(row);
}
let lastRow = sheet.getLastRow() + 1
try{
let range = sheet.getRange(lastRow, 1, table.length, table[0].length )
range.setValues(table);
} catch (err){
break
}
} while (obj.Employees.length > 0);
}
}
Try this:
function myFunction() {
// here is your object (parsed json)
var obj = {
"Employees": [
{
"User": {
"UserId": "4d132227-ea5c-4e57-b105-2f8b97872545",
"Login": "test#gmail.com",
"FullName": {
"LastName": "Фамилия",
"FirstName": "Имя",
"MiddleName": "Отчество"
},
"IsRegistered": true
},
"Permissions": {
"UserDepartmentId": "b5072e57-1e96-490b-ae03-2fd52ef84a3a",
"IsAdministrator": false,
"DocumentAccessLevel": "SelectedDepartments",
"SelectedDepartmentIds": [ "b5072e57", "cd2e04dc", "36e4434b" ],
"Actions": [
{ "Name": "CreateDocuments", "IsAllowed": true },
{ "Name": "DeleteRestoreDocuments", "IsAllowed": true },
{ "Name": "SignDocuments", "IsAllowed": true },
{ "Name": "AddResolutions", "IsAllowed": true },
{ "Name": "RequestResolutions", "IsAllowed": true },
{ "Name": "ManageCounteragents", "IsAllowed": false }
],
"AuthorizationPermission": { "IsBlocked": false }
},
"Position": "Специалист по снабжению",
"CanBeInvitedForChat": true,
"CreationTimestamp": { "Ticks": 637284074150000000 }
}
],
"TotalCount": 214
};
var table = []; // it will be the 2d array
for (var employee of obj.Employees) {
var {LastName, FirstName, MiddleName} = employee.User.FullName;
var name = [LastName, FirstName, MiddleName].join(' ');
var actions = {};
employee.Permissions.Actions.forEach(a => actions[a.Name] = a.IsAllowed);
var row = [
employee.User.UserId,
name,
employee.Position,
employee.User.Login,
employee.User.IsRegistered,
employee.Permissions.IsAdministrator,
actions.SignDocuments, // Can sign documents
actions.AddResolutions, // Can coordinate documents
actions.RequestResolutions, // Can request document approval
actions.CreateDocuments, // Can create documents and work with drafts
actions.DeleteRestoreDocuments, // Can delete documents and drafts, restore documents
actions.ManageCounteragents, // Can work with a list of counterparties
];
table.push(row); // add the row to the 2d array
}
// put the 2d array on the sheet
SpreadsheetApp.getActiveSheet()
.getRange(2,1,table.length,table[0].length)
.setValues(table);
}
Let me know if it works.

How to retrieve value in javascript

I am returning a json as shown below,
{
"entities": {
"permissions": {
"77de5140-9e1f-48b6-87a5-c80f12cd66d9": {
"id": "77de5140-9e1f-48b6-87a5-c80f12cd66d9",
"role": "ADMIN",
"permissions": null,
"canAccessAllAccounts": true,
"allowedAccounts": null,
"createdAt": "2022-01-30T18:20:46.901Z",
"updatedAt": "2022-01-30T18:20:46.901Z",
"deletedAt": null
}
},
"users": {
"9bba4c96-781b-4012-9a48-071c1cb5ec24": {
"id": "9bba4c96-781b-4012-9a48-071c1cb5ec24",
"username": "246e6555eb16e3c8#ator.com",
"activeAccountId": "a979189d-6bef-41f9-b224-892fbeb0955b",
"enterpriseId": "9a69bba9-ed35-4589-8784-6b0e256bd7a0",
"permissionId": "77de5140-9e1f-48b6-87a5-c80f12cd66d9",
"firstName": "a48d1eb7270bb404",
"lastName": "e0aaa6d09e19",
"avatarUrl": null,
"sendBookingRequestEmail": true,
"isSSO": false,
"createdAt": "2022-01-30T18:20:46.999Z",
"updatedAt": "2022-01-30T18:20:46.999Z",
"deletedAt": null,
"permission": "77de5140-9e1f-48b6-87a5-c80f12cd66d9"
}
}
},
"result": "9bba4c96-781b-4012-9a48-071c1cb5ec24"
}
I am trying to get permissionsid value (it is occurred three places in the JSON), also forgot to mention in the original comment that these alphnumeric values in permissionid and userid are dynamics
When I am using the following, I am getting undefined
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);
var permission_id = userResponseParser['permissionId'];
When I am using the following, I am getting Cannot read properties of undefined (reading 'id')
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);
var permission_id = userResponseParser.entities.permissions[0].id;
When I am using the following, I am getting undefined
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);
var permission_id = userResponseParser.entities.permissions[0];
When I am using the following, I am getting [object%20Object]
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);
var permission_id = userResponseParser.entities.permissions;
What I am missing here, couldn't find same kind of question
Why stringify and parse?
Anyway, it is more complex than you think
const obj = JSON.parse(str)
console.log(Object.values(obj.entities.users)[0].permissionId)
<script>
const str = `{
"entities": {
"permissions": {
"77de5140-9e1f-48b6-87a5-c80f12cd66d9": {
"id": "77de5140-9e1f-48b6-87a5-c80f12cd66d9",
"role": "ADMIN",
"permissions": null,
"canAccessAllAccounts": true,
"allowedAccounts": null,
"createdAt": "2022-01-30T18:20:46.901Z",
"updatedAt": "2022-01-30T18:20:46.901Z",
"deletedAt": null
}
},
"users": {
"9bba4c96-781b-4012-9a48-071c1cb5ec24": {
"id": "9bba4c96-781b-4012-9a48-071c1cb5ec24",
"username": "246e6555eb16e3c8#ator.com",
"activeAccountId": "a979189d-6bef-41f9-b224-892fbeb0955b",
"enterpriseId": "9a69bba9-ed35-4589-8784-6b0e256bd7a0",
"permissionId": "77de5140-9e1f-48b6-87a5-c80f12cd66d9",
"firstName": "a48d1eb7270bb404",
"lastName": "e0aaa6d09e19",
"avatarUrl": null,
"sendBookingRequestEmail": true,
"isSSO": false,
"createdAt": "2022-01-30T18:20:46.999Z",
"updatedAt": "2022-01-30T18:20:46.999Z",
"deletedAt": null,
"permission": "77de5140-9e1f-48b6-87a5-c80f12cd66d9"
}
}
},
"result": "9bba4c96-781b-4012-9a48-071c1cb5ec24"
}`</script>
I see only 2 places, but in any cases remove this from your code
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);
since your response data is parced already automatically
Since you can have several permissions or users , you can not get your data just using [0] or [1] since you don' t know how many users can be in the response. So try this code ( it was tested and working properly)
var permissionIds=[];
Object.values(response.entities.permissions).forEach(element => {
permissionIds.push(element.id)
});
var userIds=[];
Object.values(response.entities.users).forEach(element => {
userIds.push(element.id)
});

How to get attribute value from JSON and write it in file in specific format using node.js

I have a test.json file and It's in below format and I just want to get link value from that file:
Input file from File System:
{
"5cacd1333105": {
"type": "CORR-ID",
"environment": "amazon",
"tags": [
{
"name": "EC-6S0005704A8324S98020",
"source": "amazonstage2ma_paymentapiplatserv#TOKEN",
"flags": [
"FLAG_DYNAMIC_VALUE",
"FLAG_ID_LOOKUP_SUPPORTED"
]
}
],
"callSummary": [
{
"colo": "lvs",
"pool": "slingshotrouter",
"machine": "stage21007",
"apiName": "GET",
"status": "0",
"duration": 13400.0,
"calls": null,
"hints": null,
"msgTime": 1574314991130,
"link": "https://www.amazon.qa.pilot.com/Tid-942342192424j2j234"
},
{
"colo": "lvs",
"pool": "slingshot",
"machine": "stage21029",
"apiName": "GET",
"status": "0",
"duration": 13368.0,
"calls": null,
"hints": null,
"msgTime": 1574314991162,
"link": "https://www.amazon.qa.pilot.com/Tid-12342342i842424j2j234"
},
{
"colo": "lvs",
"pool": "msmaster_userbridgedomainserv",
"machine": "amazon1int-g_userbridgedomainserv_22",
"apiName": "POST",
"status": "0",
"duration": 15.0,
"calls": null,
"hints": null,
"msgTime": 1574315001625,
"link": "https://www.amazon.qa.pilot.com/Tid-02341723424i842424j2j290"
}
],
"partial": false
}
}
I wanna get the below details from above file:
"https://www.amazon.qa.pilot.com/Tid-942342192424j2j234"
"https://www.amazon.qa.pilot.com/Tid-12342342i842424j2j"
"https://www.amazon.qa.pilot.com/Tid-02341723424i842424"
I just want to write into test.js file as below format.
module.exports =
{
fileNames:[
'https://www.amazon.qa.pilot.com/Tid-942342192424j2j234',
'https://www.amazon.qa.pilot.com/Tid-12342342i842424j2j',
'https://www.amazon.qa.pilot.com/Tid-02341723424i842424'
]
}
I don't know how to get those details. Can someone please share me some input on this?
It looks like 5cacd1333105 is a dynamic key, so it might change, and there might be more than one random key like that, so you can use a for... in loop like this to loop each key (prop) in the object:
const d = require('./test.json');
for(let prop in d){
console.log(d[prop])
}
Then you can see that the only relevant property is callSummary array because it contains the link data. Therefore you can loop the array to extract the link data.
for(let prop in d){
const obj = d[prop];
const links = obj.callSummary.map(({link}) => link);
console.log(links);
}
The above uses destructuring inside a .map callback to extract the link string from the objects inside callSummary, returning an array of link strings in links.
However, we still need to take into account the general case of multiple links due to the outer for... in loop.
To combine the links into a single array, you can declare links outside the loops as an empty array, and just push to that array, like this:
const links = [];
for(let prop in d){
const obj = d[prop];
links.push(obj.callSummary.map(({link}) => link));
}
console.log(links);
Finally, you want to write that data into a file. You can use either fs or you could spawn / execute a command line program from within your node.js script. See https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback on how to use fs.writeFile or use child_process e.g.
const d = require('./test.json');
const path = require('path');
const { spawn } = require( 'child_process' );
const links = [];
for(let prop in d){
const obj = d[prop];
links.push(obj.callSummary.map(({link}) => link));
}
const filename = `links-${Date.now()}.js`;
console.log(`Outputting links to ${filename}`);
const echo = spawn( 'echo', [ `
module.exports =
{
fileNames:[
${JSON.stringify(links, false, 2)}
]
}
`, '>', path.join(process.cwd(), filename) ] );
Note the use of backticks. (I didn't test that last bit, but it should work).
You have not shared how you are acquiring this data, but since you added a tag for node.js, I am assuming you are doing this on the server side.
After you make sure the data you received is in JSON format (using JSON.parse) and it is valid, to get the specific fields you require, you can do the following:
let links = [];
let callSummary = json['5cacd1333105'].callSummary
for (let index = 0; index < callSummary.length; index++) {
let call = callSummary[index];
if (call && call.link) {
links.push(call.link);
}
}
After this, you will have al lthe links in the array links and you can do whatever you please with them.
This code have a little risk, but it's work in your situation
const data = {
"5cacd1333105": {
"type": "CORR-ID",
"environment": "amazon",
"tags": [
{
"name": "EC-6S0005704A8324S98020",
"source": "amazonstage2ma_paymentapiplatserv#TOKEN",
"flags": [
"FLAG_DYNAMIC_VALUE",
"FLAG_ID_LOOKUP_SUPPORTED"
]
}
],
"callSummary": [
{
"colo": "lvs",
"pool": "slingshotrouter",
"machine": "stage21007",
"apiName": "GET",
"status": "0",
"duration": 13400.0,
"calls": null,
"hints": null,
"msgTime": 1574314991130,
"link": "https://www.amazon.qa.pilot.com/Tid-942342192424j2j234"
},
{
"colo": "lvs",
"pool": "slingshot",
"machine": "stage21029",
"apiName": "GET",
"status": "0",
"duration": 13368.0,
"calls": null,
"hints": null,
"msgTime": 1574314991162,
"link": "https://www.amazon.qa.pilot.com/Tid-12342342i842424j2j234"
},
{
"colo": "lvs",
"pool": "msmaster_userbridgedomainserv",
"machine": "amazon1int-g_userbridgedomainserv_22",
"apiName": "POST",
"status": "0",
"duration": 15.0,
"calls": null,
"hints": null,
"msgTime": 1574315001625,
"link": "https://www.amazon.qa.pilot.com/Tid-02341723424i842424j2j290"
}
],
"partial": false
}
};
const jsonDAta = JSON.stringify(data,null,null);
const resArr = (jsonDAta.match(/"link":"[^"]+"/g)||[]).map(el=>JSON.parse(`{${el||''}}`).link)
console.log(resArr);

How to do nested loops with object jSON data on nodejs

I'm new use nodejs and mongodb, now I build restful API use nodejs and mongodb. I want use response standard for my API with http://jsonapi.org standard.
I need a suggestion from advance how best way to do it, making my API response like the following JSON data:
HTTP/1.1 200 OK
Content-Type: application/vnd.api+json
{
"links": {
"self": "http://example.com/users"
},
"data": [{
"type": "users",
"id": 5b647bb8998248235a0aab3c,
"attributes": {
"username": "luke",
"email": "luke#mail.com",
"password": "password",
"hashpassword":"",
"oldpassword":"$2a$10$eyt6YV6m2JJrebNxvS0iEuxMCubDXratNJ6/XK797IGvepXBdp9Yq",
"salt":"2q6eN9U0vWFBsIF1MtB5WrgPiB8pldTS",
"usertype":"bisnis",
"userstatus":"not aktif"
}
}, {
"type": "users",
"id": 5b647bdf998248235a0aab3d,
"attributes": {
"username": "ken",
"email": "ken#mail.com",
"password": "password",
"hashpassword":"",
"oldpassword":"$2a$10$eyt6YV6m2JJrebNxvS0iEuxMCubDXratNJ6/XK797IGvepXBdp9Yq",
"salt":"2q6eN9U0vWFBsIF1MtB5WrgPiB8pldTS",
"usertype":"bisnis",
"userstatus":"not aktif"
}
}]
}
I have problem with nest iteration when create output as above. This my code:
const UsersModel = mongoose.model('Users');
//...show list user
exports.listUsers = (req, res) => {
UsersModel.find({}, (err, result) => {
if (err) {
res.send({code: 400, failed: 'Error 400'});
}
res.json(result);
});
};
And this is my result JSON:
[
{
"type": "users",
"userstatus": "not aktif",
"_id": "5b647bb8998248235a0aab3c",
"username": "luke",
"email": "luke#mail.com",
"password": "password",
"usertype": "bisnis",
"hashpassword": "$2a$10$eyt6YV6m2JJrebNxvS0iEuxMCubDXratNJ6/XK797IGvepXBdp9Yq",
"salt": "2q6eN9U0vWFBsIF1MtB5WrgPiB8pldTS",
"__v": 0
},
{
"type": "users",
"userstatus": "tidak aktif",
"_id": "5b647bdf998248235a0aab3d",
"username": "ken",
"email": "ken#mail.com",
"password": "password",
"usertype": "personal",
"hashpassword": "$2a$10$hok988mszyIBiXVNjmfifOiPNzXkBRRRynXJS/0qCkvlaBOQs65MO",
"salt": "IiMvtVYVqTpZFXmYQIM4IlS6PJFVZ3kw",
"__v": 0
}
]
And this is my temporary code for my problem.
//...show list user
exports.listUsers = (req, res) => {
UsersModel.find({}, (err, result) => {
if (err) {
res.send({code: 400, failed: 'Error 400'});
}
let listData = [];
for (let key in result) {
let data = {};
let attr = {};
if (result.hasOwnProperty(key)) {
data.type = result[key].type;
data.id = result[key]._id;
for(let i in result[key]) {
if(result[key].hasOwnProperty(i)) {
attr.username = result[key].username;
attr.email = result[key].email;
attr.password = result[key].password;
attr.hashpassword = result[key].hashpassword;
attr.oldpassword = result[key].oldpassword;
attr.salt = result[key].salt;
attr.usertype = result[key].usertype;
attr.userstatus = result[key].userstatus;
}
}
data.attribute = attr;
listData.push(data);
}
}
let collections = {
"meta": {
"copyright": "Copyright 2018 Kotakku Studio and Lab",
"authors": [
"sw. saputra"
]
},
"link": {
"self": req.protocol + '://' + req.get('host') + req.originalUrl
},
"data": listData
}
res.json(collections);
});
};
Please give me suggestion the elegant and the best way to solve my problem if my temporary code is not correct.
Thanks advance.
You need to create a proper mongoose schema according to your requirement and map the res to the schema.
//Schema for users
var UsersSchema = mongoose.Schema({
links: {
self: String
},
data:[{
type: String,
attributes: {
username: String,
.
.
.
}
}]
})
id for each document in an array will be created automatically by MongoDB.
For mongoose schema docs see http://mongoosejs.com/docs/guide.html
You can also check this simple TODO API for reference https://github.com/mkujaggi/node-course-todo-api
In this condition's statement:
if(result[key].hasOwnProperty(i)) {
You should be accessing the i of result[key]:
if(result[key].hasOwnProperty(i)) {
attr.username = result[key][i].username;
attr.email = result[key][i].email;
attr.password = result[key][i].password;
attr.hashpassword = result[key][i].hashpassword;
attr.oldpassword = result[key][i].oldpassword;
attr.salt = result[key][i].salt;
attr.usertype = result[key][i].usertype;
attr.userstatus = result[key][i].userstatus;
}
And you don't need all those .hasOwnProperty checks unless you're modifying native prototypes, which you probably shouldn't. And especially for the Array, it's not necessary if you'd just loop properly with a for instead of a for-in.
exports.listUsers = (req, res) => {
UsersModel.find({}, (err, result) => {
if (err) {
res.send({
code: 400,
failed: 'Error 400'
});
}
let listData = [];
let data = {};
let attr = {};
data.type = result[key].type;
data.id = result[key]._id;
for (let i = 0; i < result[key].length; i++) {
attr.username = result[key][i].username;
attr.email = result[key][i].email;
attr.password = result[key][i].password;
attr.hashpassword = result[key][i].hashpassword;
attr.oldpassword = result[key][i].oldpassword;
attr.salt = result[key][i].salt;
attr.usertype = result[key][i].usertype;
attr.userstatus = result[key][i].userstatus;
}
data.attribute = attr;
listData.push(data);
}
}
let collections = {
"meta": {
"copyright": "Copyright 2018 Kotakku Studio and Lab",
"authors": [
"sw. saputra"
]
},
"link": {
"self": req.protocol + '://' + req.get('host') + req.originalUrl
},
"data": listData
}
res.json(collections);
});
};
I would do something like this with iterating over the keys (this will work dynamically that is even if we don't know key names)
var test=[
{
"type": "users",
"userstatus": "not aktif",
"_id": "5b647bb8998248235a0aab3c",
"username": "luke",
"email": "luke#mail.com",
"password": "password",
"usertype": "bisnis",
"hashpassword": "$2a$10$eyt6YV6m2JJrebNxvS0iEuxMCubDXratNJ6/XK797IGvepXBdp9Yq",
"salt": "2q6eN9U0vWFBsIF1MtB5WrgPiB8pldTS",
"__v": 0
},
{
"type": "users",
"userstatus": "tidak aktif",
"_id": "5b647bdf998248235a0aab3d",
"username": "ken",
"email": "ken#mail.com",
"password": "password",
"usertype": "personal",
"hashpassword": "$2a$10$hok988mszyIBiXVNjmfifOiPNzXkBRRRynXJS/0qCkvlaBOQs65MO",
"salt": "IiMvtVYVqTpZFXmYQIM4IlS6PJFVZ3kw",
"__v": 0
}
]
var listData=[]
test.forEach((obj)=>{
var tempObj={attributes:{}}; //initialize tempObj
Object.keys(obj).forEach((key)=>{
if(key=="_id" || key=="type"){
tempObj[key]=obj[key];
}else{
tempObj.attributes[key]=obj[key];
}
})
listData.push(tempObj);
})
let collections = {
"meta": {
"copyright": "Copyright 2018 Kotakku Studio and Lab",
"authors": [
"sw. saputra"
]
},
"link": {
"self": 'test url'
},
"data": listData
}
console.log(collections)

json to javascript variable zendesk

I'm trying to retrieve the amount of open tickets from the zendesk api for a specific user. However I can't seem to get it to work. I keep getting this error:
Uncaught TypeError: Cannot read property '500' of undefined
The json format:
{
"user": {
"id": 500,
"url": "https://zendesk/api/v2/users/500.json",
"name": "Random name",
"email": "not important",
"created_at": "2016-05-18T15:26:43Z",
"updated_at": "2018-07-04T06:23:35Z",
"time_zone": "Brussels",
"phone": null,
"shared_phone_number": null,
"photo": {
"url": "https://google.com",
"id": 504,
"file_name": "keep-calm-and-shut-up-im-your-system-administrator.png",
"content_url": "https://google.com",
"mapped_content_url": "https://google.com",
"content_type": "image/png",
"size": 3298,
"width": 80,
"height": 50,
"inline": false,
"thumbnails": [
{
"url": "https://google.com",
"id": 90752965,
"file_name": "not important",
"content_url": "https://google.com",
"mapped_content_url": "https://google.com",
"content_type": "image/png",
"size": 3298,
"width": 32,
"height": 20,
"inline": false
}
]
},
"locale_id": 1005,
"locale": "nl",
"organization_id": 501,
"role": "admin",
"verified": true,
"external_id": null,
"tags": [],
"alias": "",
"active": true,
"shared": false,
"shared_agent": false,
"last_login_at": "2018-07-04T06:23:35Z",
"two_factor_auth_enabled": null,
"signature": "",
"details": "",
"notes": "",
"role_type": null,
"custom_role_id": null,
"moderator": true,
"ticket_restriction": null,
"only_private_comments": false,
"restricted_agent": false,
"suspended": false,
"chat_only": false,
"default_group_id": 503,
"user_fields": {
"agent_ooo": false
}
},
"open_ticket_count": {
"500": 15
}}
This is my javascript code:
<script>
function getJSON(url) {
var resp ;
var xmlHttp ;
resp = '' ;
xmlHttp = new XMLHttpRequest();
if(xmlHttp != null)
{
xmlHttp.open( "GET", url, false );
xmlHttp.send( null );
resp = xmlHttp.responseText;
}
return resp ;
}
var gjson ;
gjson = getJSON('https://zendesk.com//api/v2/users/me.json?
include=open_ticket_count');
console.log(gjson.open_ticket_count["500"]);
</script>
Can someone help me out? I'm not sure of what I'm doing wrong (the zendesk urls are the correct urls in the actual script and they can access it)
TLDR: I need to retrieve the variable from: open_ticket_count from a json.
Thank you!
Your getJSON function will not wait for the request to actually go through. A function like this would return the responseText only once it's finished:
const getJSON = function(url, callback) {
let xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
let status = xhr.status;
if (status === 200) {
callback(null, xhr.response);
} else {
callback(status, xhr.response);
}
};
xhr.send();
};
You can then use this to get the Zendesk JSON:
getJSON('https://zendesk.com//api/v2/users/me.json?include=open_ticket_count', (status, gjson) => {
console.log(gjson.open_ticket_count["500"]);
});
Hard to say exacty without rest of the environment but I assume this will work:
var gjson ;
gjson = getJSON('https://zendesk.com//api/v2/users/me.json?include=open_ticket_count'');
var jsonObj = JSON.parse(gjson); // assuming getJSON returns the json as string, this is async, make sure next row has the data needed on time or rewqork this as promise
console.log(jsonObj.open_ticket_count["500"]);
So basically call the entire JSON and then parse it from string to object before using it like object
The clue is in the error
Uncaught TypeError: Cannot read property '500' of undefined
Which says that gjson.open_ticket_count is undefined.
You haven't actually parsed the JSON and trying to get a property of a string not the parsed JSON.
Try parsing it first.
var gjson;
gjson = getJSON('https://zendesk.com//api/v2/users/me.json?include=open_ticket_count');
var gobj = JSON.parse(gjson);
console.log(gobj.open_ticket_count["500"]);
You need to parse the JSON in order to access it. Use below code
<script>
function getJSON(url) {
var resp ;
var xmlHttp ;
resp = '' ;
xmlHttp = new XMLHttpRequest();
if(xmlHttp != null)
{
xmlHttp.open( "GET", url, false );
xmlHttp.send( null );
resp = xmlHttp.responseText;
}
return resp ;
}
var gjson ;
gjson = getJSON('https://zendesk.com//api/v2/users/me.json?
include=open_ticket_count');
gjson = JSON.parse(gjson)
console.log(gjson.open_ticket_count["500"]);
</script>

Categories

Resources