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);
});
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'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!
This is the data displaying in console.log.
{"data":
[
{
"CloserName":null,
"agent_id":"10807",
"AgentName":"TEST",
"SurveyDate":"02/02/2018 02:18:46 AM",
"SurveyName":"Ruth ",
"state":"West Bengal",
"phone":"9836969715",
"status":"Approved",
"verification_progress":"Pending",
"survey_id":"1",
"rejection_remarks":"aa",
"tl_remarks":"Pending"
}
],
"count":1
}
Can anyone help me display a single value (i.e survey_id)? I just want to fetch that survey_id
Here's an example:
var json = {
"data":[
{
"CloserName":null,
"agent_id":"10807",
"AgentName":"TEST",
"SurveyDate":"02/02/2018 02:18:46 AM",
"SurveyName":"Ruth ",
"state":"West Bengal",
"phone":"9836969715",
"status":"Approved",
"verification_progress":"Pending",
"survey_id":"1",
"rejection_remarks":"aa",
"tl_remarks":"Pending"
}
],
"count":1
}
// get first id
var id = json.data[0].survey_id
console.log(id)
// get all ids
var ids = json.data.map(x => x.survey_id)
console.log(ids)
If the JSON is stringified, call JSON.parse(jsonStr) first.
You have to parse the JSON-String into an object. After that you can access the data with default object-identifiers.
const object = JSON.parse('{"data":[{"CloserName":null,"agent_id":"10807","AgentName":"TEST","SurveyDate":"02/02/2018 02:18:46 AM","SurveyName":"Ruth ","state":"West Bengal","phone":"9836969715","status":"Approved","verification_progress":"Pending","survey_id":"1","rejection_remarks":"aa","tl_remarks":"Pending"}],"count":1}');
console.log(object.data[0].survey_id)
If your JSON data has been stringified (your sample JSON is a valid JSON object, not a string) you would first need to parse it, and then get the IDs (assuming you will have more than one item inside the data array) and log them out. There's a few different ways of achieving this:
const stringified = '{"data":[{"CloserName":null,"agent_id":"10807","AgentName":"TEST","SurveyDate":"02/02/2018 02:18:46 AM","SurveyName":"Ruth ","state":"West Bengal","phone":"9836969715","status":"Approved","verification_progress":"Pending","survey_id":"1","rejection_remarks":"aa","tl_remarks":"Pending"}],"count":1}';
let parsed = JSON.parse(stringified);
parsed = parsed.data.map(item => item.survey_id);
console.log(parsed);
You can also just loop over the items in the array and log them one by one using a for loop:
const stringified = '{"data":[{"CloserName":null,"agent_id":"10807","AgentName":"TEST","SurveyDate":"02/02/2018 02:18:46 AM","SurveyName":"Ruth ","state":"West Bengal","phone":"9836969715","status":"Approved","verification_progress":"Pending","survey_id":"1","rejection_remarks":"aa","tl_remarks":"Pending"}],"count":1}';
let parsed = JSON.parse(stringified);
for (let i = 0; i < parsed.data.length; i++) {
console.log(parsed.data[i].survey_id);
}
Or using a for-of:
const stringified = '{"data":[{"CloserName":null,"agent_id":"10807","AgentName":"TEST","SurveyDate":"02/02/2018 02:18:46 AM","SurveyName":"Ruth ","state":"West Bengal","phone":"9836969715","status":"Approved","verification_progress":"Pending","survey_id":"1","rejection_remarks":"aa","tl_remarks":"Pending"}],"count":1}';
let parsed = JSON.parse(stringified);
for (const item of parsed.data) {
console.log(item.survey_id);
}
According to your current object structure
Your object
var obj = {"data":[{"CloserName":null,"agent_id":"10807","AgentName":"TEST","SurveyDate":"02/02/2018 02:18:46 AM","SurveyName":"Ruth ","state":"West Bengal","phone":"9836969715","status":"Approved","verification_progress":"Pending","survey_id":"1","rejection_remarks":"aa","tl_remarks":"Pending"}],"count":1};
Fetching survey_id
obj.data[0].survey_id
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
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...