i'm using firebase function.
the code like this.
let transaction_id;
let signature_key;
switch (req.get('Content-Type')) {
case 'application/json':
({transaction_id} = req.body);
({signature_key} = req.body);
break;
case 'application/octet-stream':
transaction_id = req.body.toString();
signature_key = req.body.toString();
break;
case 'text/plain':
transaction_id = req.body;
signature_key = req.body;
break;
case 'application/x-www-form-urlencoded':
({transaction_id} = req.body);
({signature_key} = req.body);
break;
}
console.log(transaction_id);
it still showing undefined.
console log req.body not showing json response.
the i try to JSON.Stringify.
Transaction status is pending {"transaction_id":"1c133665-d73d-45b6-b183-8d263644736b","signature_key":"TzbgFmtPe5qLu1MPcId3MoRcyU%2FBRWHJ6AdQQdLHN6ABy0SpB56F4jYUPFLMemPYL8KhruaQvWWYpAUEXJhcnpQ0Qn%2FHbE0GRwx1Em3Hc%2FWi1mofPUafALccvUmRR3QE","status":"OK","amount":"1020000.00","shipping_address":{},"payment_type":"30_days","transaction_status":"pending","transaction_time":1593094347,"order_id":"P-2020237834543138"}
when i do JSON.stringify it show up above data.
how to remove text outside curly bracket {} so i can convert to json to get value on transaction_id and signature_key?
or how to get the data directly from JSON.stringify output?
If you want to get the the transaction_id and signature_key from the JSON, you can do this
var parsedData = JSON.parse(yourJsonString);
var transaction_id = parsedData.transaction_id
var signature_id = parseedData.signature_id;
Not sure, but is this what you want?
If you want to ommit the data before and after the outer curly brackets, then i would suggest to run an regex
str.replace(/^[^{]*(.*)[^}]*$/,'$1');
And the result can be put into the JSON.prase function.
Summary:
let trx_id = JSON.parse(result.replace(/^[^{]*(.*)[^}]*$/,'$1')).transaction_id;
Related
I want to parse this JSON array and print the salary so this what I have tried so far
there is nothing logged in the Console
if (data.action == 'SendArray') {
let invites = data.invites
const obj = JSON.parse(invites)
const myJSON = JSON.stringify(obj);
console.log(myJSON.salary)
}
JSON:
{"factioname":"sp-force","inviter":"MohammedZr","salary":5000},
{"factioname":"air-force", "inviter":"Admin","salary":8000}
This const myJSON = JSON.stringify(obj) turns your object back into a string, which you don't want.
I've done some setup to get your data matching your code but the two things you should note are:
Iterating through the array of invites using for .. of (you could use forEach instead) and
Using deconstruction to pull out the salary
data = { action: 'SendArray'
, invites: '[{"factioname":"sp-force","inviter":"MohammedZr","salary":5000},{"factioname":"air-force", "inviter":"Admin","salary":8000}]'
}
if (data.action == 'SendArray') {
let invites = data.invites
const obj = JSON.parse(invites)
for ({salary} of JSON.parse(invites))
console.log(salary)}
myJSON is an array of objects. To log in console need to get each object. we can use forEach to get each object and then can console log the salary key.
let myJSON =[
{"factioname":"sp-force","inviter":"MohammedZr","salary":5000},
{"factioname":"air-force", "inviter":"Admin","salary":8000}];
myJSON.forEach(obj=> {
console.log(obj.salary);
});
I'm trying to access data from a json but i can't... I have tried some explanations i found on the internet, but i guess there is something wrong on my code.
I'm getting data from a sql server database using the following code:
async function getLogin1(Operador, Senha) {
try {
let pool = await sql.connect(config);
let getLogin1 = await pool.request()
.input('input_parameter', sql.VarChar, Operador)
.input('input_parameter1', sql.VarChar, Senha)
.query("SELECT Codigo, Operador, Senha FROM Usuario where Operador = #input_parameter and Senha = #input_parameter1");
return getLogin1.recordsets;
}
catch (error) {
console.log(error);
}
}
So i get the recordsets here and put in a json:
router.route("/Login1").get((request, response) => {
console.log(request.body.operador);
console.log(request.body.senha);
Operador = request.body.operador;
Senha = request.body.senha;
dboperations.getLogin1(Operador, Senha).then(result => {
console.log(Operador, Senha);
response.json(result);
var json = JSON.stringify(result);
console.log(json);
})
})
On the console it shows the json:
[[{"Codigo":1,"Operador":"Username","Senha":"123456"}]]
I would like to get the individual data (codigo, operador and senha) to put in a individual string each one, but i cant access the data.
When I try like json[0] for example i get all the json (because my json has every info on the first position i guess), and when i try json.Codigo (for example) i get a "undefined" error.
What am i doing wrong and what the best way to solve?
And sorry for the low knowledge, this is my very first api.
(And yes, this is a login code and its not the best way to treat user data but its a very small system for intern use)
Your JSON "result" is:
[[{"Codigo":1,"Operador":"MASTER","Senha":"TERA0205"}]]
So it is an array of array containing one object with keys Codigo, Operador, Senha.
To get the value of the Codigo of that object you would likely need to
access it like
var CodigoVal = result[0][0].Codigo; // 1
var OperadorVal = result[0][0].Operador; // "MASTER"
Looks like json has nested array, if so json[0] will give inner array so you have to probably do like json[0][0].Codigo
[
[
{ "Codigo":1,
"Operador":"Username",
"Senha":"123456"
}
]
]
If we look at the JSON you posted above, we have an array which has an array with an object at its first index.
So to get access to that object you need to do:
const obj = json[0][0];
Now from obj you can extract Codigo, Operado and Senha like
const condigo = obg.Condigo;
const operado = obg.Operado;
const senha = obg.Senha;
You can also directly access them like
var codigo = json[0][0].Codigo;
var operador = json[0][0].Operador;
var senha = json[0][0].Senha;
json.Codigo doesnt work because your json has a array in it. Which has the object you are trying to get data from.
json[0] returns everything because that gives you the object from that array
so if you want Codigo try json[0][0].Codigo
I hope this helped you!
i have a realtime database from firebase with 9386 datasets in it (but that might change in the future)
thats why i want to know whats the "key" of the last event.
thats how i'm currently trying to get it to know: (with npm module qwest)
let order = "\u0022\u0024key\u0022";
let dbUrl = "https://example.firebaseio.com/users.json?limitToLast=1&orderBy=";
let end;
qwest.get(dbUrl + order)
.then(function(xhr, response) {
console.log(response);
end = response[9386]["username"];
console.log(end);
});
first question: why do i have to escape the quotation marks and the dollarsign?
second question: how can i get the "key" of the last item i'm checking for in the json (limitToLast=1).
json response looks like this:
{"9386":
{
"fromListA":"1",
"fromListB":"0",
"id":"9939",
"lastChecked":"2019-05-09 03:18:05",
"userid":"123456789",
"username":"username"
}
}
and i want to get the "9386" in a variabel.
Since you chose to use " to limit the dbUrl string, you can't use " inside that string's value without escaping it. A simpler way to define the string is to use ' to delimit it:
let dbUrl = 'https://example.firebaseio.com/users.json?limitToLast=1&orderBy="$key"';
To get the key of the object, use something like:
Object.keys(response)[0]
var response = {"9386":
{
"fromListA":"1",
"fromListB":"0",
"id":"9939",
"lastChecked":"2019-05-09 03:18:05",
"userid":"123456789",
"username":"username"
}
}
console.log(Object.keys(response)[0]);
My API returning the JSON value like
[{"UserName":"xxx","Rolename":"yyy"}]
I need Username and RoleName value seperatly i tried JSON.parse but its returning [Object Object] Please help me thanks in advance
Consider the following:
var str = '[{"UserName":"xxx","Rolename":"yyy"}]'; // your response in a string
var parsed = JSON.parse(str); // an *array* that contains the user
var user = parsed[0]; // a simple user
console.log(user.UserName); // you'll get xxx
console.log(user.Rolename); // you'll get yyy
If your data is a string then you need to parse it with JSON.parse() otherwise you don't need to, you simply access it as is.
// if data is not in string format
const data = [{"UserName":"xxx","Rolename":"yyy"}];
const username = data[0].UserName
const rolename = data[0].Rolename
console.log(username)
console.log(rolename)
// if data is in string format
const strData = JSON.parse('[{"UserName":"xxx","Rolename":"yyy"}]');
const Username = strData[0].UserName
const Rolename = strData[0].Rolename
console.log(Username)
console.log(Rolename)
You have an array. Then need to get 0th element very first
This will work
let unps = JSON.parse('[{"UserName":"xxx","Rolename":"yyy"}]')[0]
console.log(unps.UserName, unps.Rolename);
when saving an array of objects as a JSON, you need to use the following format in Sample.txt to not run into parsing errors:
[{"result":"\"21 inches = 21 inches\"","count":1},{"result":"\"32 inches = 32 inches\"","count":2}]
I'm new to JSON and searching over this for since last 4 days. I tried different approaches of storing an array of objects but no success. My first and simplest try is like this:
function createData() {
//original, single json object
var dataToSave = {
"result": '"' + toLength.innerText +'"',
"count": counter
};
//save into an array:
var dataArray = { [] }; //No idea how to go ahead..
var savedData = JSON.stringify(dataToSave);
writeToFile(filename, savedData); //filename is a text file. Inside file, I want to save each json object with , in between. So It can be parsed easily and correctly.
}
function readData(data) {
var dataToRead = JSON.parse(data);
var message = "Your Saved Conversions : ";
message += dataToRead.result;
document.getElementById("savedOutput1").innerText = message;
}
To make an array from your object, you may do
var dataArray = [dataToSave];
To add other elements after that, you may use
dataArray.push(otherData);
When you read it, as data is an array, you can't simply use data.result. You must get access to the array's items using data[0].result, ... data[i].result...