Get data from the response - javascript

I have a response which is of the below format,
{
"access_token": "eWcWLctGW-_NgGVAmFbO9l-nt3yztFzlZCLLlilI9mGDcM5q8d0kQw0uzvFOoXynHcb-MuPVJGTGkSkBhrr69_-aN1r5j9zB4fCl4u4aqOQ-scNI36xgHeGYpXky60drIBpMI83FGqd9pMjL4GWXjFHq61nhJ6xkGj1u1r9a5u6EJrB1lfjNhljzC_j65xaqxtubQ4AglKFO2ib-levpvnd_bEU-QGQrtvS2QbaXhb_hlnX8czo61Gn_OQyBVk7HbN1SozxIPe3RBvf5AiCAouDMz1WMHy9ybVFy8SnoNIgszjo7Ev2IEWS9aFb87u6bvoJvSVJv7s3z-2GUvG2kwfOk2sUWrmq0QeIJJrYwdKQfs3T8HrK2MNKSGteJ04-O",
"token_type": "bearer",
"expires_in": 1799,
"refresh_token": "f1005c7fd74247069dbdb078ee379410",
"as:client_id": "438dc832-33c7-413b-9c71-d0b98a196e6a",
"userName": "master",
".issued": "Fri, 20 Jan 2017 14:30:09 GMT",
".expires": "Fri, 20 Jan 2017 15:00:09 GMT"
}
I'm not sure how to access .issued , .expires and as:client_id
I'm using angular and passing username, password and company_id and getting the response in the above format.
dataService.getAuthToken($scope.username, $scope.password, $scope.company_password).then(function (response) {
//response data here
});
I can easily get token_type, access_token by just using response.data.access_token but not sure how to access .issued , .expires and as:client_id

You can access every property of an object in JavaScript by the indexer syntax, like if it was a map (because an object is a map in javascript):
var issued = response.data[".issued"];
var expires = response.data[".expires"];
var asClient_id= response.data["as:client_id"];
See this link: http://www.w3schools.com/js/js_objects.asp
Accessing Object Properties
You can access object properties in two ways:
objectName.propertyName
or
objectName["propertyName"]

Related

sending data in correct format from react to node

I have a date object in my state coming from a react-datepicker component.
Sat Aug 28 2021 18:00:00 GMT+0530 (India Standard Time)
On Submit I am trying to pass this to my Node backend
try {
const responseData = await sendRequest('http://localhost:5000/challenge/createChallenge', 'POST',
JSON.stringify({
location: selectedOption,
format: selectedOption1,
date: selectedDate,
opponent: props.initialValues
}),
{
'Content-Type': 'application/json',
Authorization: 'Bearer ' + auth.token
})
Using Stringify, it loses its form. The date loses 5.5 hours and becomes a string.
date: '2021-08-24T12:30:00.000Z'
how do I preserve the original IST format while sending it across? I tried removing the Json.stringify but it keeps erroring me out.
I think if you send a date object to backend as below, your problem will be sorted out
date: new Date(yourDate)
and remove that JSON.stringify.
Not sure if this is the right solution but I passed the data with to.String() and its now getting received accurately in NODE. Thanks.
JSON.stringify({
location: selectedOption,
format: selectedOption1,
date: selectedDate.toString(),
opponent: props.initialValues
}),

How to create a Timestamp and Geopoint instance in Firebase Emulator from browser console

I have create a mock data and performed a batch update with firestore.batch(). The problem is that location is saved as a number and time as a string and not as Geopoint and Timestamp instances respectively, causing my React app to crash.
I could see that only firestore is accessible through window.firestore, but not Firebase. Since Firebase isn't exported as window.firebase, I cannot create either Geopoint or Timestamp instance.
So, how to create a Timestamp and Geopoint instance in Firebase Emulator from browser console?
Here's a type of doc I'm adding to firestore
const doc = {
"company": "company-1",
"location": [
-72.3623, // number
79.5748 // but, want to convert to Geopoint instance
],
"time": "Fri Sep 10 1976 07:42:23 GMT+0530 (India Standard Time)", // string
"createdAt": "Mon Apr 28 2014 13:30:16 GMT+0530 (India Standard Time)", // want to convert to Timestamp
}
A more dependable accessor path than .Gf:
new firestore.app.firebase_.firestore.GeoPoint(lat, lng)
There's a firebase accessible through window.firestore.
So I figured a way to create Geopoint and Timestamp instance through Firestore.
You can access it through window.firestore.Gf.firebase_, through which you can create those both instance.
const raw = // pasting from clipboard
const batch = firestore.batch()
const firebase = firestore.Gf.firebase_
const Timestamp = firebase.firestore.FieldValue().Timestamp
const GeoPoint = firebase.firestore.FieldValue().GeoPoint
raw.forEach(doc => {
const docRef = firestore
.collection('user')
.doc('user-1')
.collection('interviews')
.doc()
doc = {
...doc,
time: Timestamp.fromDate(new Date(doc.time)),
createdAt: Timestamp.fromDate(new Date(doc.createdAt)),
location: new GeoPoint(doc.location[0], doc.location[1])
}
batch.set(docRef, doc)
})
batch.commit()

Converting XML to JSON and output to HTML with jQuery

I'm trying to test out an idea I had but using this XML to JSON script:
https://github.com/sergeyt/jQuery-xml2json
But then take the JSON data and then output that into HTML with jQuery.
So far, I've been able to load up the data correctly and I can console.log out the JSON data which turns out to be something like this:
releases:
$: {}
matching_count: "698"
returned_count: "50"
latestModified: "1537876805"
release: Array(50)
0:
$: {}
id: "713"
headline: "Eiger BioPharmaceuticals to Participate in Investor Conferences"
released: "1537876800"
releaseDate: "Tue, 25 Sep 2018 08:00:00 -0400"
modified: "1537876805"
modifiedDate: "Tue, 25 Sep 2018 08:00:05 -0400"
1:
$: {}
id: "712"
headline: "Communications industry innovator to speak at AMEC Global Summit"
released: "1491400800"
releaseDate: "Wed, 05 Apr 2017 10:00:00 -0400"
modified: "1491400806"
modifiedDate: "Wed, 05 Apr 2017 10:00:06 -0400"
...
My JS code that I have so far is this:
var ul = $("<ul>").appendTo("body");
$.ajax({
url: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/8689/list.xml",
dataType: "xml",
success: function(response) {
json = $.xml2json(response);
console.log(json);
$(json).each(function(index, headline) {
ul.append($(document.createElement("li")).text(headline));
});
}
});
The issue is that when it renders out, all that comes back is [object Object] in a single li.
So, I know that I'm doing something incorrectly, but I'm not sure where and at what point I need to change over to get the data so I can render out the headline, releaseDate, and so on.
I've created a Codepen here:
https://codepen.io/ultraloveninja/pen/YzPRjRw
I've read that I might need to use jQuery.parseJSON but after testing that a bit, I get some errors since it's still getting in that object.Object again.
I feel that I need to drill down a bit more to get within the releases.release somehow since that's where all the data is at to be rendered out.
The response you try to loop is an object representing the xml document.
To access the releases array you have to use json["#document"].releases.release
var ul = $("<ul>").appendTo("body");
$.ajax({
url: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/8689/list.xml",
dataType: "xml",
success: function(response) {
json = $.xml2json(response);
let release = json["#document"].releases.release
$(release).each(function(index, headline) {
ul.append($(document.createElement("li")).text(headline.headline));
});
}
});
Example

How can I access json data inside array?

I need some help for a json value. I data is -
[
{
"statusCode":200,
"body":{
"token":"xxxxx"
},
"headers":{
"date":"Thu, 28 Jul 2016 11:03:17 GMT",
"server":"Apache/2.2.15 (CentOS)",
"x-powered-by":"PHP/5.6.22",
"cache-control":"private, must-revalidate",
"etag":"\"9517ef72d528ad7a3bc04c64d1cc1cc9\"",
"set-cookie":[
"XSRF-TOKEN=xxx; expires=Thu, 28-Jul-2016 13:03:17 GMT; Max-Age=7200; path=/",
"laravel_session=eyJpdiI6IkZITXdyTGtpZlRkc1hmQkptUWpZSEE9PSIsInZhbHVlIjoicGxLUmJxRzlcL2dGTTdVcVJiQ1g2QTh4enQxdDI5NElCbGJkVllKYVR0MG1LQTljaFhhUFJSUVVXTytheUxqajZjV3FVUkh2SUhPK0ZtelhIQjcxVk5nPT0iLCJtYWMiOiJkOTg1MWFiYjY5ZTdhNThkODk5N2Y1MmRlOWEwZWMwYWQ4MGE4ZDVjMWRjMGMwNjA0MTlmNjQ1YzNmNDM3NWVkIn0%3D; expires=Thu, 28-Jul-2016 13:03:17 GMT; Max-Age=7200; path=/; httponly"
],
"vary":"Accept-Encoding",
"content-length":"305",
"connection":"close",
"content-type":"application/json"
},
"request":{
"uri":{
"protocol":"http:",
"slashes":true,
"auth":null,
"host":"api.shobkichhu.com",
"port":80,
"hostname":"api.shobkichhu.com",
"hash":null,
"search":null,
"query":null,
"pathname":"/api/auth/login",
"path":"/api/auth/login",
"href":"http://api.shobkichhu.com/api/auth/login"
},
"method":"POST",
"headers":{
"content-type":"application/json",
"accept":"application/json",
"content-length":45
}
}
},
{
"token":"xxxx"
}
]
I need to access token. How can I access token ?
Thanks in advance
This is the solution
var data =[
{
"statusCode":200,
"body":{
"token":"xxxxx"
},
},
{
"token":"xxxx"
}
];
console.log(data[0].body.token); // for first token
console.log(data[1].token); // for second token
var myObj = [
{
body:
{
token : 'xxxxxxx'
}
},
{
other : 'aaa'
}
];
console.log(myObj[0].body.token);
//or other version
var bodyObj = myObj.find(function(item){ return item && item.body});
console.log(bodyObj.body.token);
Assuming you have parsed the JSON (and that it's valid JSON, which it isn't in the question) and assigned the result to data, you access it like this:
data[0].body.token
...because:
data refers to an array
[0] accesses the first entry in the array, which refers to an object
.body accesses that object's body property value, which refers to another object
.token accesses that object's token property value
E.g.:
var json = '[{"body":{"token":"xxxxxxx"}},{"other":"aaa"}]';
var data = JSON.parse(json)
console.log(data[0].body.token);

Inquiry on Node.js HTTP requests/responses and URL as primary key for this JSON-formatted document

I have a script that uses Node.js to request headers from a specific site.
var http = require("http");
var fs = require("fs");
var hostNames = ['www.google.com'];
var options = {
host: hostNames[i],
path: '/'
};
http.get(options, function(res) {
var obj = {};
obj.statusCode = res.statusCode;
obj.headers = res.headers;
console.log(JSON.stringify(obj, null, 4));
})
The output, for the URL "www.google.com" would be attached below:
{
"statusCode": 200,
"headers": {
"date": "Mon, 04 Mar 2013 16:43:39 GMT",
"expires": "-1",
"cache-control": "private, max-age=0",
"content-type": "text/html; charset=ISO-8859-1",
"set-cookie": [
"PREF=ID=cfa31a2cae817ca6:FF=0:TM=1362415419:LM=1362415419:S=m-sNTevwPhFFWVpv; expires=Wed, 04-Mar-2015 16:43:39 GMT; path=/; domain=.google.com",
"NID=67=AKMqJ9Q94GtcmF0kTOAOLgFLqz9XAnSwVe4jzzXFVhvxuxRJP_l9QEwbjR3F7d506thF9BURyGJUz5DuNTEzXesit50Dm7FlOoVuL2qGRt9XZwRMGjAlxL5heO4vIATp; expires=Tue, 03-Sep-2013 16:43:39 GMT; path=/; domain=.google.com; HttpOnly"
],
"p3p": "CP=\"This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info.\"",
"server": "gws",
"x-xss-protection": "1; mode=block",
"x-frame-options": "SAMEORIGIN",
"transfer-encoding": "chunked"
}
}
My question is in-regards to JSON. I am trying to store the output into MongoDB. MongoDB stores JSON-like documents. From my understanding, SQL-based databases have a primary key. This is where my confusion comes in. I would like to use the URL, in this case, 'www.google.com' as the primary key. How do I achieve this? This is my first time using JSON-like storing structures, and the multiple articles I have read do not really apply to my specific situation.
When I search for "www.google.com" in the database, the plan is to have the headers show up, under "www.google.com." I don't know - I think I am still thinking in the SQL mindset. Can someone share some insight to this?
Here is official docs on object ids.
So you can create your own object id for a record using anything with appropriate format (hex number) and length, so this will work
db.names.insert({"_id": new ObjectId("012345678901234567890123"), "name" : "my name" })
but this dont
db.names.insert({"_id": new ObjectId("my reallllly long string"), "name" : "my name" })
you will need to use hash of your url if you want to using at object id.
However mongo gives you another option. leave _id field alone and create url field for url, and than set index on url field
db.scrapedPages.ensureIndex({ 'url': 1})
UPDATE: more specifically to your example.
You are not going to set/change _id property, mongo does it for you.
Instead you are going set url property of document to save, and reasonable thing to use here is your options object, as it defines the page you are parsing.
So I think you'll endup with something like that ( I expect you use mongo native driver and have mongo connection open )
var options = {
host: hostNames[i],
path: '/'
};
http.get(options, function(res) {
var obj = {
url: options.host + options.path // or whatever else is
statusCode : res.statusCode,
headers : res.headers
}
save(obj, function(err, objects) {
if (err) console.warn(err.message);
})
})
function save(doc, callback) {
var collection = new mongodb.Collection(client, 'test_collection')
, cb = callback || function() {}
collection.insert(doc, {safe:true}, cb);
}
The primary key in an SQL table is a column that is used to uniquely identify a particular row. In mongodb _id is the field which is the primary key. mongodb adds it automatically if you don't specify it and assigns an ObjectId (12 byte long BSON identifier) to it. You can check the details here.

Categories