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);
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 JSON response like this
const json = '{"arr":[{"key1": "value1"},{"key2": "value2"}], "m":[{"key3": "value3"},{"key4": "value4"}], "b":[{"key5": "value5"},{"key6": "value6"}]}'
I need an array like this
const array = [{"key1": "value1"},{"key2": "value2"},{"key3": "value3"},{"key4": "value4"},{"key5": "value5"},{"key6": "value6"}]
how can I achieve that?
Tough to test with the data you supplied as it is neither valid JSON or valid JS objects. But generally speaking you want to go inside an object and spread all its keys' values. Here is the code to do that:
const json = '{"arr":[{"key1": "value1"},{"key2": "value2"}], "m":[{"key3": "value3"},{"key4": "value4"}], "b":[{"key5": "value5"},{"key6": "value6"}]}'
const obj = JSON.parse(json);
const result = [];
Object.values(obj).map(item => result.push(...item))
console.log(result);
Again, I had to create a valid JSON string for it to work.
Also, please note that this is not a valid JS array: [{1},{2},{3},{4},{5},{6}]
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
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);