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!
Related
I need to extract data from json response using Javascript. I have checked posts but couldnt find a fitting solution for my problem. The json:
{"apple":{"count":4},"orange":{"messageCount":3},"banana":{"messageCount":2},"grapes":{"messageCount":5}}
I have tried to get the count of each item, eg apple using the below code:
const obj = JSON.parse(txt);
document.getElementById("demo").innerHTML = obj[0];
But returns undefined.
How can i acheive the count of each fruit and store in a variable using Javascript. Thanks
use the JSON.parse() method and store it in the data and get count of each fruit by accessing property of the data object
const response = '{"apple":{"count":4},"orange":{"messageCount":3},"banana":{"messageCount":2},"grapes":{"messageCount":5}}';
const data = JSON.parse(response);
const appleCount = data.apple.count;
const orangeCount = data.orange.messageCount;
const bananaCount = data.banana.messageCount;
const grapesCount = data.grapes.messageCount;
console.log(appleCount);
console.log(orangeCount);
console.log(bananaCount);
console.log(grapesCount);
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 followed this little how to to apply a simple api in nodejs. It is not quite my area of expertise, I am a Computer Network Analyst and although I develop applications in C ++ (simple) and C #, I have a small doubt on how to obtain the result of an array returned by the following code:
Javascript Code using Mysql ->
//
exports.findAll = (req, res) => {
const name = req.query.name;
var condition = name ? { name: { [Op.like]: `%${name}%` } } : null;
Custumers.findAll({ where: condition })
.then(data => {
res.send(data);;
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving name."
});
});
};
Access to URL to check if everything goes as expected.
http://10.1.1.254:8085/api/custumers?name=Gabriel
My result:
[
{"id":6,
"name":"Gabriel",
"cod":10,
"igCustumer":"1",
"createdAt":null,
"updatedAt":null}
]
How could I get the values of name, cod, imgCustumer?
Im try;
axios.get(`http://10.1.1.254:8085/api/custumers?name=Gabriel`).then((res) => {
let myvar = `My result:\n\n${res.data.name}`;
console.log(myvar);
})
Result if : Undefinid
You can access object values in JavaScript like this...
let res = [{"id":6,
"name":"Gabriel",
"cod":10,
"igCustumer":"1",
"createdAt":null,
"updatedAt":null}]
let name = res[0].name;
let cod = res[0].cod;
let igCustomer = res[0].igCustumer;
Because res is an array full of objects, you access an object with its location in the index, like res[0]. From there you can select the key/value pair in your object by using dot notation or brackets. Each method has its use.
Try something like this:
let res = [
{"id":6,
"name":"Gabriel",
"cod":10,
"igCustumer":"1",
"createdAt":null,
"updatedAt":null}
]
console.log(res[0]['name']);
console.log(res[0]['cod']);
console.log(res[0]['igCustumer']);
The problem with your code that you are trying to access a field that does not exists. The res.data will be equal to the response of your endpoint. Your response is an array, so apparently it does not have name field. So you need to take a particular object.
const user = res.data[0]; // Taking the first user.
Then you can access its data.
user.name; // Gabriel
To find data from array, you can iterate that array and use find like this :
let res = [
{id:6,
name:"Gabriel",
cod:10,
igCustumer:"1",
createdAt:null,
updatedAt:null}
]
let myVar = res.find((item) => {
return item.name === 'Gabriel'
});
console.log(myVar.name);
console.log(myVar.cod);
console.log(myVar.igCustumer);
I am new to JSON and concepts. I want to extract the data from an API which i have mentioned below, basically i want to extract several details from this API about an Stock. The problem here is, after parsing the URL i dont know how to extract the value for each variablle.
I want to extract the data into an GoogleSheet.
the output of the below function shows, like this
[20-12-10 20:45:15:806 CET] [{symbol=JMIA, price=37.0497, volume=1.317713E7}]
The output i wanted is that:
JMIA
37.0497
1.317713E7
Code :
function CurrentPrice() {
var url = 'https://financialmodelingprep.com/api/v3/quote-short/JMIA?
apikey=7c2f5bcb573b33050c1aad41a54919';
var response = UrlFetchApp.fetch(url);
// convert json string to json object
var jsonSignal = JSON.parse(response);
Logger.log(jsonSignal);
}
I suggest you read this "Working with Objects" article.
The response is wrapped in brackets [] meaning it's an array. I assume you're only expecting one response, so you can grab that first element using jsonSignal[0], which will give you an object.
To get an object property, you have to specify the property name using either dot- or bracket-notation. (I'll use dot-notation.)
const jsonSignal = [{symbol:'JMIA', price:37.0497, volume:1.317713E7}];
console.log(jsonSignal[0].symbol); // 'JMIA'
function CurrentPrice() {
const url = 'https://financialmodelingprep.com/api/v3/quote-short/JMIA?apikey=API_KEY';
const response = UrlFetchApp.fetch(url);
// Convert HTTPResponse
// Use the first element in the response array
const signal = JSON.parse(response)[0];
console.log(signal.symbol); // 'JMIA'
console.log(signal.price); // 37.0497
console.log(signal.volume); // 1.317713E7
}
Try like this :
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(data);
I read that there : https://developers.google.com/apps-script/guides/services/external
Regards
I have a control that returns 2 records:
{
"value": [
{
"ID": 5,
"Pupil": 1900031265,
"Offer": false,
},
{
"ID": 8,
"Pupil": 1900035302,
"Offer": false,
"OfferDetail": ""
}
]
}
I need to test via Postman, that I have 2 records returned. I've tried various methods I've found here and elsewhere but with no luck. Using the code below fails to return the expected answer.
responseJson = JSON.parse(responseBody);
var list = responseBody.length;
tests["Expected number"] = list === undefined || list.length === 2;
At this point I'm not sure if it's the API I'm testing that's at fault or my coding - I've tried looping through the items returned but that's not working for me either. Could someone advise please - I'm new to javascript so am expecting there to be an obvious cause to my problem but I'm failing to see it. Many thanks.
In postman, under Tests section, do the following (screenshot below):
var body = JSON.parse(responseBody);
tests["Count: " + body.value.length] = true;
Here is what you should see (note: I replaced responseBody with JSON to mock up example above):
Correct your json. and try this.
=======================v
var test = JSON.parse('{"value": [{"ID": 5,"Pupil": 1900031265,"Offer": false},{"ID": 8,"Pupil": 1900035302,"Offer": false,"OfferDetail": ""}] }')
test.value.length; // 2
So you need to identify the array in the json (starting with the [ bracket. and then take the key and then check the length of the key.
Here's the simplest way I figured it out:
pm.expect(Object.keys(pm.response.json()).length).to.eql(18);
No need to customize any of that to your variables. Just copy, paste, and adjust "18" to whatever number you're expecting.
This is what I did for counting the recods
//parsing the Response body to a variable
responseJson = JSON.parse(responseBody);
//Finding the length of the Response Array
var list = responseJson.length;
console.log(list);
tests["Validate service retuns 70 records"] = list === 70;
More updated version of asserting only 2 objects in an array:
pm.test("Only 2 objects in array", function (){
pm.expect(pm.response.json().length).to.eql(2);
});
Your response body is an object you cannot find the length of an object try
var list = responseJson.value.length;
First of all you should convert response to json and find value path. Value is array. You should call to length function to get how many objects in there and check your expected size
pm.test("Validate value count", function () {
pm.expect(pm.response.json().value.length).to.eq(2);
});
I had a similar problem, what I used to test for a certain number of array members is:
responseJson = JSON.parse(responseBody);
tests["Response Body = []"] = responseJson.length === valueYouAreCheckingFor;
To check what values you're getting, print it and check the postman console.
console.log(responseJson.length);
Counting records in JSON array using javascript and insomnia
//response insomnia
const response = await insomnia.send();
//Parse Json
const body = JSON.parse(response.data);
//Print console:
console.log(body.data.records.length);
pm.test("Only 2 objects in array", function (){
var jsonData = pm.response.json();
let event_length = jsonData.data.length;
pm.expect(event_length).to.eql(2);
});
As mentioned in the comments, you should test responseJson.value.length
responseJson = JSON.parse(responseBody);
tests["Expected number"] = typeof responseJson === 'undefined' || responseJson.value.length;
I was facing similar issue while validating the length of an array inside a JSON. The below snippet should help you resolve it-
responseJson = JSON.parse(responseBody);
var list = responseBody.length;
tests["Expected number"] = responseJson.value.length === list;
Working Code
pm.test("Verify the number of records",function()
{
var response = JSON.parse(responseBody);
pm.expect(Object.keys(response.value).length).to.eql(5);
});
//Please change the value in to.eql function as per your requirement
//'value' is the JSON notation name for this example and can change as per your JSON