Extract Value from Json string in Ionic 2 - json

I am using OAuth2 for authorization in my Ionic 2 App and the decoded token response(which I am getting from the BASE64.decode() function) is like the below(key-value form).I am storing it in a variable called 'tokendata' of type 'any'. Now I want to extract values from this decoded token. Now if I simply do 'tokendata.personnelnbr', it is not working. Also if I do a 'json.parse(tokendata) or a json.parse('tokendata'), store it in another variable say 'myVar' and then try to access 'myVar.personnelnbr', then also it is not working. Please help with the solution!
{
"client_id":"xxx",
"scope":"user_profile",
"sub":"yyy",
"amr":"external",
"auth_time":1499753830,
"idp":"eso_enterprise",
"upn":"yyy",
"email":"yyy",
"samaccount_name":"yyy",
"peoplekey":"1169",
"personnelnbr":"1108",
"given_name":"Deblina",
"sn":"Dutta Chowdhury",
"exp":1499,
"nbf":1499
}
The method where I am trying to access the 'personnelnbr' field is given below:
private initializeApp(): void
{
this.platform.ready().then(() => {
console.log("Before login Deblina");
/**
* Read in app configuration, get an oAuthV1 ESO token, register device with REBAR Notification Services
*/
this.configService.Initialize().subscribe(
() => this.esoService.getV2Token().subscribe(
(v2Token) => {
this.tokendata = BASE64.decode(v2Token);
alert("Token Deblina decoded: " + BASE64.decode(v2Token));
console.log("Token Deblina decoded: " + BASE64.decode(v2Token));
this.concatenatedToken = "'" +this.tokendata+ "'";
alert(this.concatenatedToken);
console.log(this.concatenatedToken);
this.myVar = JSON.parse(this.tokendata);
alert("Now:" + this.myVar.personnelnbr);
console.log("Now:" + this.myVar.personnelnbr);
this.myVar = JSON.parse(this.concatenatedToken);
alert("Now:" + this.myVar.personnelnbr);
console.log("Now:" + this.myVar.personnelnbr);
},
(error) => console.log(error),
() => { this.nav.setRoot(HomePage)}
),
(error) => console.log(error)
);
});
}

If you just want to to extract value, you can do this:
let datas = {
"client_id":"xxx",
"scope":"user_profile",
"sub":"yyy",
"amr":"external",
"auth_time":1499753830,
"idp":"eso_enterprise",
"upn":"yyy",
"email":"yyy",
"samaccount_name":"yyy",
"peoplekey":"1169",
"personnelnbr":"1108",
"given_name":"Deblina",
"sn":"Dutta Chowdhury",
"exp":1499,
"nbf":1499
};
for (let key in datas) {
console.log(key + " => " + datas[key]);
}

Related

Res.Json returns duplicated array

I'm using react js with express as backend and mysql.
When i'm trying to show the data from the database with the next query I notice in the console of the browser that res.json returns two arrays
This is the code to get the data
export const allVehiculos = async (req,res) => {
try {
var query= "SELECT `idVehiculos`, `placa`, `codip`, `descp`, `anio`, `clase`, `color`, `motor`, `serie`, `marca` " +
"FROM vehiculos AS vehiculos " +
"INNER JOIN marcas as marcas " +
"on `Vehiculos`.`idMarca` = `marcas`.`id`"
const vehiculos = await db.query(query)
res.json(vehiculos)
} catch (error) {
res.json({message: error.message})
}
}
This is the code of the react component
const [vehiculos, setVehiculo] = useState([])
useEffect( () => {
getVehiculos();
}, [])
return(
vehiculos.map((item) => {
return(
<tr key={item.idVehiculos} className="table-row row-item">
<td>{item.placa}</td>
<td>{item.codip}</td>
<td>{item.descp}</td>
<td>{item.anio}</td>
<td>{item.clase}</td>
<td>{item.color}</td>
<td>{item.motor}</td>
<td>{item.serie}</td>
<td>{item.marca}</td>
</tr>
)})
)
Result of res.json
Info not showing
But, when I change
res.json(vehiculos)
to
res.json(vehiculos[0])
Then i got just one array and the information shows correctly
Info showing correctly
I don't know why res.json returns two arrays and how to get only one array
Sorry for my bad english,
I'm very new in this field.
Thanks.

How to make html_url into hyperlinks from fetch/json

I am learning javascript and Json so please bear with me.
I have fetched certain json data and made it visible on my webpage. All this through my GitHub api. I have three repositories in total and each contain the name of the repository a description and a html_url. I would like to make the three html_url active. So the user can click directly on them and go to that repository. I've been trying and googling but have yet to have any success. Any tips would be hugely appreciated.
Below is my js code.
`
function load () {
element = document.getElementById("gitRepos");
element.classList.toggle("hide");
const loadingStatus = document.querySelector('#gitRepos')
let url = "https://api.github.com/users/PaulEvans78/repos"
async function getrepo() {
let response = await fetch(url);
const repoList = document.getElementById("gitRepos")
const links = document.getElementById("gitRepos")
if(response.ok) {
let data = await response.json();
loadingStatus.innerText = " "
console.log(data);
for (const item of data){
createRepoLi(repoList, item.name, item.html_url, item.description)
}
} else {
console.log("HTTP-Error: " + response.status);
}
}
function createRepoLi(repoList, name, html_url, description){
const li = document.createElement('li')
li.innerText = name + "\n " + html_url + "\n " + description
li.classList.add("gitHubStyle");
repoList.appendChild(li)
}
getrepo();
}
`

Invalid Json Response when accessing third-party service with Wix Corvid

I am attempting to gather details about real estate properties through an external API. I've gone over their documentation relentlessly but can not figure out why I am receiving the following error:
invalid json response body at https://api.gateway.attomdata.com/propertyapi/v1.0.0/property/expandedprofile?address1=34%20Karen%20Court&address2=Bridgeport20%CT reason: Unexpected token < in JSON at position
For reference, I am posting my code. If anyone can provide any input or guidance I would greatly appreciate it!
Backend Code:
import { fetch } from 'wix-fetch';
import { wixData } from 'wix-data';
export function getDetails(address, citystatezip) {
const url = 'https://api.gateway.attomdata.com/propertyapi/v1.0.0/property/expandedprofile?address1=' + address + "&address2=" + citystatezip;
let headers = {
"apikey": "xxxxxxxx",
"accept": "application/json"
};
let options = {
headers: headers
}
console.log("Url: " + url);
return fetch(url, { method: 'get' })
.then(response => {
return response.json();
})
.then((data) => {
console.log(data);
return data;
});
}
Page Code:
wixWindow.getCurrentGeolocation()
.then((obj) => {
let timestamp = obj.timestamp; // 1495027186984
let latitude = obj.coords.latitude; // 32.0971036
let longitude = obj.coords.longitude; // 34.774391099999995
let altitude = obj.coords.altitude; // null
let accuracy = obj.coords.accuracy; // 29
let altAccuracy = obj.coords.altitudeAccuracy; // null
let heading = obj.coords.heading; // null
let speed = obj.coords.speed;
console.log(obj)
reverse(latitude, longitude)
.then(geocode => {
console.log(geocode)
let id = geocode.results[0].place_id;
details(id)
.then(detailed => {
console.log(detailed)
$w("#input12").value = geocode.results[0].address_components[0].long_name + " " + geocode.results[0].address_components[1].long_name;
$w("#input10").value = geocode.results[0].address_components[3].long_name;
$w("#input11").value = geocode.results[0].address_components[5].long_name;
$w("#text37").text = geocode.results[0].formatted_address;
$w("#googleMaps2").location = {
"latitude": latitude,
"longitude": longitude,
"description": geocode.results[0].formatted_address
};
let address = geocode.results[0].address_components[0].long_name + " " + geocode.results[0].address_components[1].long_name;
let city = geocode.results[0].address_components[3].long_name;
let state = geocode.results[0].address_components[5].short_name;
let citystate = city +"%2C" + "%20" + state;
console.log(citystate)
const uri = address;
const encoded = encodeURI(uri);
console.log(encoded);
getDetails(encoded, citystate)
.then(got => {
console.log(got)
})
});
});
Thank you in advance for any input or guidance you can offer. I have spent hours trying to figure this out to no avail.
Stay safe and stay well 😊

Cannot read property 'json' of undefined

why is it not getting result ? The sql query is simple and correct and works in mysql
const getDateBw = (InvoiceDate1, InvoiceDate2, err, req, res) => {
let startDate = new Date(InvoiceDate1);
let endDate = new Date(InvoiceDate2);
let formattedDate1 = JSON.stringify(dateFormat(startDate, "yyyy-mm-dd"));
let formattedDate2 = JSON.stringify(dateFormat(endDate, "yyyy-mm-dd"));
console.log(formattedDate1);
db.query(
"SELECT * FROM dashboard WHERE Invoice_Date BETWEEN " +
formattedDate1 +
" " +
"AND " +
formattedDate2
).then(function (myTableRows) {
res.json({
myTableRows,
});
});
};
getDateBw("2009-05-21", "2021-01-01");
{"level":50,
"time":1598543997608,
"pid":10772,
"hostname":"Ghadi-Mdallal",
"stack":"TypeError: Cannot read property 'json' of undefined\n at C:\\Users\\LENOVO\\Desktop\\Dashboard-V1\\empServer\\handlers\\user.controllers\\user.controllers.js:29:9\n at processTicksAndRejections (internal/process/task_queues.js:97:5)",
"type":"Error",
"msg":"Cannot read property 'json' of undefined"
}
You are not passing "res" in getDateBw("2009-05-21", "2021-01-01");
How will res.json work inside? It will give "Cannot read property 'json' of undefined" error.

Flutter put request for Database

I am working on a Flutter app. we have a PSQL database, Node server on the background. On the Flutter app I am displaying some geometry which I fetch from the database successfully. Now after a modification on the geometry, such as lines, I want to be able to update the database via a put request.
Server goes like:
app.put('/api/shape/:id', async (req,res) =>{
let answer;
if( req.body.shape_type == "line"){
answer = await db.db.modify_line(req.params.id, req.body.info_shape);
}
res.send(answer);
});
And db.js file goes like:
modify_line : async function(id_shape, info_shape){
console.log(info_shape);
const result = await send_query("UPDATE line SET line = $2 WHERE id_shape = $1", [id_shape, info_shape]);
return(result);
},
On the Flutter app I do this:
_makeUpdateRequest() async {
var url = globals.URL + 'api/shape/' + globals.selectedShapeID.toString();
Map data;
if (globals.selectedType == globals.Type.line) {
String lseg = "(" + globals.pLines[globals.selectedLineIndex].p1.dx.toString() + "," +
globals.pLines[globals.selectedLineIndex].p1.dy.toString() + "," +
globals.pLines[globals.selectedLineIndex].p2.dx.toString() + "," +
globals.pLines[globals.selectedLineIndex].p2.dy.toString() + ")";
data = {
'shape_type': 'line',
'info_shape': {
'id_shape': globals.selectedShapeID.toString(),
'line': lseg,
}
};
}
http.Response response;
try {
//encode Map to JSON
print("encode Map to JSON");
var body = json.encode(data);
print(body);
response =
await http.put(url,
headers: {
"Content-Type": "application/json"
},
body: body
).catchError((error) => print(error.toString()));
} catch (e) {
print(e);
}
return response;
}
Database "line" table contains a "shapeID" and "lseg" information on each row.
Currently I am getting an error when I try this code:
{ id_shape: '619',
line: '(19.5,100.6,20.5,50.9)' }
fail____error: invalid input syntax for type lseg: "{"id_shape":"619","line":"(-19.5,100.6,20.5,50.9)"}"
How shall I shape my lseg json?
Thanks
Well, it looks like to me you are passing the whole input_shape object to the SQL query, which looks like this, as per your console.log:
{
id_shape: '619',
line: '(19.5,100.6,20.5,50.9)'
}
Obviously, this is invalid for PostgreSQL.
I would say that your backend code should be more like this:
modify_line : async function(id_shape, info_shape){
console.log(info_shape);
const result = await send_query(
"UPDATE line SET line = $2 WHERE id_shape = $1",
// Reference "line" sub-object
[id_shape, info_shape.line],
);
return(result);
},
You should also pay attention to the Geometric types format for lines:
[ ( x1 , y1 ) , ( x2 , y2 ) ]
( ( x1 , y1 ) , ( x2 , y2 ) )
( x1 , y1 ) , ( x2 , y2 )
x1 , y1 , x2 , y2
I'm not 100% sure by reading this that your format (with leading and trailing parenthesis) is correct.
As the issue is solved, following is the answer:
DB.js is like:
modify_line : async function(id_shape, info_shape){
const result = await send_query("UPDATE line SET line = $2 WHERE id_shape = $1", [info_shape['id_shape'], info_shape['line']]);
return(result);
},
and Flutter app is like:
_makeUpdateRequest() async {
var url = globals.URL + 'api/shape/' + globals.selectedShapeID.toString();
Map data;
if (globals.selectedType == globals.Type.line) {
String lseg =
"[" + globals.pLines[globals.selectedLineIndex].p1.dx.toString() + "," +
globals.pLines[globals.selectedLineIndex].p1.dy.toString() + "," +
globals.pLines[globals.selectedLineIndex].p2.dx.toString() + "," +
globals.pLines[globals.selectedLineIndex].p2.dy.toString() + "]";
data = {
'shape_type': 'line',
'info_shape': {
'id_shape': globals.selectedShapeID.toString(),
'line': lseg,
}
};
}
http.Response response;
try {
//encode Map to JSON
print("encode Map to JSON");
var body = json.encode(data);
print(body);
response =
await http.put(url,
headers: {
"Content-Type": "application/json"
},
body: body
).catchError((error) => print(error.toString()));
} catch (e) {
print(e);
}
return response;
}