Storing data from JSON object received from Google People Api - javascript

So I have a server that receives data from Google People api regarding contacts and my received object has the following structure:
{ connections:
[ { resourceName: 'people/c3904925882068251400',
etag: '%EgYBAgkLNy4aDQECAwQFBgcICQoLDA0iDFZUOUE0NkRBZW0wPQ==',
names:
[ { metadata: { primary: true, source: [Object] },
displayName: 'Mihai Vrincut',
familyName: 'Vrincut',
givenName: 'Mihai',
displayNameLastFirst: 'Vrincut, Mihai' },
{ metadata: { source: [Object] },
displayName: 'Mihai Vrincut',
familyName: 'Vrincut',
givenName: 'Mihai',
displayNameLastFirst: 'Vrincut, Mihai' } ],
emailAddresses:
[ { metadata: { primary: true, source: [Object] },
value: 'mihai.vrincut#gmail.com' } ] },
{ resourceName: 'people/c3275206487406036814',
etag: '%EgYBAgkLNy4aDQECAwQFBgcICQoLDA0iDHBFVzBUMm8wWU5nPQ==',
names:
[ { metadata: { primary: true, source: [Object] },
displayName: 'aaaaaaaaa',
givenName: 'aaaaaaaaa',
displayNameLastFirst: 'aaaaaaaaa' } ] },
{ resourceName: 'people/c5777943907795350059',
etag: '%EgYBAgkLNy4aDQECAwQFBgcICQoLDA0iDGxOeGYwblg3bFUwPQ==',
names:
[ { metadata: { primary: true, source: [Object] },
displayName: 'costin',
givenName: 'costin',
phoneticFamilyName: 'cancius',
phoneticGivenName: 'costin',
displayNameLastFirst: 'costin' } ],
emailAddresses: [ { metadata: { primary: true, source: [Object] }, value: 'hj' } ],
phoneNumbers:
[ { metadata: { primary: true, source: [Object] },
value: '07543532512',
canonicalForm: '+40754353251' } ] } ], totalPeople: 3}totalItems: 3 }
In order to get this object I used the util.inspect() method. However, when I try to access the names for example, I get undefined:
var response=util.inspect(responses,{depth:5});
Console.log(response.connections[0].names);
What is wrong?

So, given the situation, and the information you've given over the comment sections.
I assume that responses is already an object, but util.inspect, makes it a string with a JSON kind of syntax but without the quotes (") before and after the names of the keys. That's why you get
{ connections: ^ SyntaxError: Unexpected token c in JSON at position 2
So, try going over the responses object.
console.log(responses)
And get the name of the keys. With them
console.log(responses.sth.sthElse.anotherSth.anotherSthElse.lastSth.connections)
And see if you get the expected result :)

You should convert the response to JSON Object.
try this:
console.log(JSON.parse(response).connections[0].names);
(I am assuming you are working in Javascript)

What I would do is validate if the answer is a String, you have a
console.log (typeof response)
if it is a string, convert it to JSON:
let responseObject = JSON.parse (response);
Finally, try if you can access the object:
console.log (responseObject.connections [0] .names);
You tell me your answer :)

Related

Calling a JSON key that has a non-letter character

I am trying to return the value of #microsoft.graph.downloadUrl from the json object below:
[
{
'#microsoft.graph.downloadUrl': 'https://public.bl.files.1drv.com/XXXX',
createdDateTime: '2021-07-10T06:14:31.03Z',
cTag: 'QQQQ',
eTag: 'SSSS',
id: 'FFFF',
lastModifiedDateTime: '2021-07-12T09:27:21.69Z',
name: 'FILE_NAME',
size: 98580,
webUrl: 'https://1drv.ms/b/SSSS',
reactions: { commentCount: 0 },
createdBy: { application: [Object], user: [Object] },
lastModifiedBy: { user: [Object] },
parentReference: {
driveId: 'XXX',
driveType: 'personal',
id: 'YYYY!YYY',
name: 'Documents',
path: '/drive/root:/Documents'
},
file: { mimeType: 'application/pdf', hashes: [Object] },
fileSystemInfo: {
createdDateTime: '2021-07-10T06:14:31.03Z',
lastModifiedDateTime: '2021-07-12T09:27:21.69Z'
}
}
]
I wish to use something like this that i had done to extract the name as I need to be able to get the #microsoft.graph.downloadUrl from each json object (known as f below) in 'files'.
var fileName = (JSON.stringify(files[f].name));
I tried both:
var fileURL = (JSON.stringify(files[f]."#microsoft.graph.downloadUrl"));
var fileURL = (JSON.stringify(files[f].#microsoft.graph.downloadUrl));
but neither work -- any help would be much appreciated!
You should just use files[f]["#microsoft.graph.downloadUrl"].

How to remove everything underneath a key from a JSON object

I have a JSON (All under req.body) in the format
{body :
{ Cust : {...} },
{ Input : {...} },
{ Reciept : {image: [Array] } }
}
I want to be able to remove all the key Reciept so the new JSON would look like ...
{body :
{ Cust : {...} },
{ Input : {...} }
}
I've tried to use delete req.body.Reciept and delete req.body.Reciept.image
Both are unable to change the JSON for me.
What should I be doing?
edit:
When I console log req.body this is what I get :
{ body:
{ CustData:
{ customer: 'T',
address1: '',
address2: '',
billing: '',
signature: [Object] },
InputData:
{ InputDate: '2019-10-21 23:25:28',
Workers: [],
Equipment: [],
Purchases: [] },
Reciept: { image: [Array] } } }
I haven't found a solution because I have a JSON and then an array as a value for a key. I am simply trying to remove the whole Reciept key and everything attached to it.
Here is what is I am running
console.log(req.body);
delete req.body.Receipt;
console.log(req.body);
Here is what I get returned in the terminal
{ body:
{ CustData:
{ customer: 'Test',
address1: '',
address2: '',
billing: '',
signature: [Object] },
InputData:
{ InputDate: '2019-10-22 0:9:33',
Workers: [],
Equipment: [],
Purchases: [] },
Receipt: { image: [Array] } } }
//followed by
{ body:
{ CustData:
{ customer: 'Test',
address1: '',
address2: '',
billing: '',
signature: [Object] },
InputData:
{ InputDate: '2019-10-22 0:9:33',
Workers: [],
Equipment: [],
Purchases: [] },
Receipt: { image: [Array] } } }
JSON-> javascript object notation. It is just an object with key and value .Ntg else. Treat is as object nothing more specific than that. you have clearly one object which holds key as body and data is object which have nested key and value pair.
Since the JSON format is text only, it can easily be sent to and from a server, and used as a data format by any programming language.
JavaScript has a built in function to convert a string, written in JSON format, into native JavaScript objects:
JSON.parse()
So, if you receive data from a server, in JSON format, you can use it like any other JavaScript object.Hope this will clear you concept of json.
delete request.body.Reciept; It is working.

Node.js - Access key from object

I try to access a key from an object I get back from an API but when I do so, I get the key of the object in a strange format.
This is what I get when I console.log the object (booking):
{ createdDate: 2018-03-26T11:36:09.694Z,
date: 2018-03-26T13:45:00.000Z,
...,
vouchers:
List [
{ value: 100,
code: 'vouchercode',
...
}
]
}
When I then try to console.log the "vouchers" key:
booking.vouchers
I get this:
{ [Function: f]
_receiver: {
createdDate: 2018-03-26T11:36:09.694Z,
date: 2018-03-26T13:45:00.000Z,
...,
vouchers: List [ [Object] ] },
_scope:
{ where: { bookingId: 5ab8db29b24991b50704445a },
collect: 'voucher',
include: 'voucher' },
_targetClass: 'Voucher',
find: [Function],
getAsync: [Function],
...,
}
Why do I get it in this format and how do I convert it to a normal object like this?:
vouchers: [
{ value: 100,
code: 'vouchercode',
...
}
]
I hope the problem is understandable and some of you can help :)
Edit:
This is my code:
Booking.findById id, {include:[ 'vouchers']}, (err, booking)->
console.log booking
vouchers = booking.vouchers
console.log vouchers
*Note: I know this is coffeescript but I don't think thats the problem

XML Attribute not working in Node.js xml2js

I'm trying to parse XML with Node.js and xml2js. In the documentation is says that $ is the character to access attributes. It doesn't seem to be working in my case.
The object result.ApiResponse.CommandResponse works fine. But anything I put afterwards is undefined.
Here's my code, it says $ is undefined :
var xml2js = require('xml2js');
var util = require('util');
var parser = new xml2js.Parser();
var xml = '<ApiResponse Status="OK"><Errors/><Warnings/><RequestedCommand>namecheap.domains.check</RequestedCommand><CommandResponse Type="namecheap.domains.check"><DomainCheckResult Domain="us.xyz" Available="true" ErrorNo="0" Description="" IsPremiumName="true" PremiumRegistrationPrice="13000.0000" PremiumRenewalPrice="13000.0000" PremiumRestorePrice="65.0000" PremiumTransferPrice="13000.0000" IcannFee="0.0000" EapFee="0.0000"/></CommandResponse><Server>PHX01APIEXT01</Server><GMTTimeDifference>--5:00</GMTTimeDifference><ExecutionTime>4.516</ExecutionTime></ApiResponse>';
parser.parseString(xml, function (err, result) {
console.log(util.inspect(result.ApiResponse.CommandResponse.DomainCheckResult.$.Available, false, null))
});
Here's the console.log(result):
{ ApiResponse:
{ '$': { Status: 'OK' },
Errors: [ '' ],
Warnings: [ '' ],
RequestedCommand: [ 'namecheap.domains.check' ],
CommandResponse:
[ { '$': { Type: 'namecheap.domains.check' },
DomainCheckResult:
[ { '$':
{ Domain: 'us.xyz',
Available: 'true',
ErrorNo: '0',
Description: '',
IsPremiumName: 'true',
PremiumRegistrationPrice: '13000.0000',
PremiumRenewalPrice: '13000.0000',
PremiumRestorePrice: '65.0000',
PremiumTransferPrice: '13000.0000',
IcannFee: '0.0000',
EapFee: '0.0000' } } ] } ],
Server: [ 'PHX01APIEXT01' ],
GMTTimeDifference: [ '--5:00' ],
ExecutionTime: [ '4.516' ] } }
It looks like CommandResponse and DomainCheckResult are actually arrays, so you need to access their first elements using [0] before digging deeper into your data.
console.log(util.inspect(
result.ApiResponse.CommandResponse[0].DomainCheckResult[0].$.Available,
false, null
))

Nested Javascript Object : recursion and "complex" transformation (with lodash)

I apologize in advance for the complex example here; I tried to trim it down as much as I could to illustrate what I try to achieve
I have a complex structure that I need to traverse and transform based on some conditions; Here's an (short) example of the structure that should cover most scenarios:
{ PROP1: {
metadata: Object, // somewhere deeper in metadata I have a `value` key
parent: { $ref: String },
employee: {
parent: { $ref: String },
id: String,
metadata: Object,
products: {
metadata: Object,
model: { $ref: String },
type: 'array',
value: ["String", "String" , "String"] ,
[...]
},
model: {
id: String,
email: {
metadata: Object,
value: 'a#b.com',
type: 'string',
validity: Object,
[...]
},
name: {
firstName: {
metadata: Object,
value: 'John',
type: String,
validity: Object,
[...]
},
lastName: {
metadata: Object,
value: 'Smith',
type: String,
validity: Object,
[...]
},
}
},
operations: {
id: String,
items: [
{ action: {value: "UPDATE", model: {$ref: String }, [...] },
{...}
],
metadata: Object,
[...]
}
}
},
PROP2: {
// similar as PROP1
},
[... and so on ...]
}
I basically need to clean that up before sending it to the backend;
Whenever a value contains $ref, I don't want the key/val pair (e.g.: PROP1.parent is of no use and can be omitted)
whenever a value contains value, I need to omit everything else and move the value of value as the value of key (e.g.: PROP1.employee.products should equal ['String', 'String', 'String'])
keys like id, metadata, validity (etc) can be completely omitted regardless of its content
So the end result should be along those lines:
{ PROP1: {
employee: {
products: ['item','item','item'],
model: {
email: 'a#b.com',
name: { firstName: 'John', lastName: 'Smith'},
},
operations: [
{action: 'UPDATE'}
]
}
},
PROP2: { ... }
}
I tried lots of different approaches using different lodash methods but couldn't wrap my head around this...
Any help will be greatly appreciated
Thanks
In pseudo code, try something like this. Implement the specifics and post more info when you run into trouble.
var ignoreKeyArray = ["id", ...] // keys to ignore and remove
var newJSON = "{}";
for (property in JSON) {
var newProp = parseJSON(key, property);
insert newProp in newJSON object
}
var parseJSON = function (key, jsonBlob) {
if (key in ignoreKeyArray || jsonBlob contains value "$ref")
return "";
var jsonOut = key + ": {}";
for (child in jsonBlob) {
add parseJSON(child) to jsonOut;
}
return jsonOut;
}
If you have any questions, comment so I can extend the answer and clarify.

Categories

Resources