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}]
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 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 large json file that needs to have to "fields" merged in to an array in order to store to firestore.
Here a screenshot to show what I mean. What i have:
What I need:
As you can see GRP1D and GRP2D where merged in to an array. The json has 15000 entries so doing it manually is not an option
You can write a script using NodeJS to edit this huge file similar to the following:
const largeJson = require('./largeJson.json');
// I am assuming here that the large JSON file is an array of objects
const mergedJson = largeJson.map(obj => {
const objEditted = { ...obj, GRP1D: [ obj.GRP1D, obj.GRP2D ] };
delete objEditted.GRP2D;
return objEditted;
});
// mergedJson now holds an array of objects which merge the fields
// GRP1D and GRP2D as you described in the example
Here is small code snippet using the spread operator
const your_data = require("./your_data/ file/path");
const prepare_func = (your_data)=>{
let temp = {...your_data,"GRP1D":[your_data["GRP1D"],your_data["GRP2D"]]};
return temp;
}
let new_data = prepare_func(your_data);
I am working with an auth token with I receive from a third-party API. I have given a sample of the decoded token below,
{
"nbf": 1564128888,
"exp": 1564132488,
"iss": "http://example.com:5002",
"aud": "http://example.com:5002/resources",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress": "Micky#gmail.com",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": "Micky Mouse",
"amr": ["custom"]
}
I am struggling to read the "name" claim in javascript. How can I read that property in javascript or typescript?
You can access complex property names like this:
const name = token["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"]
You could also abstract this away for reusability (like the ClaimTypes in C#)
const ClaimTypes = {
name: "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",
// other relevant claims
};
const name = token[ClaimTypes.name];
You will get your data in form of a string, convert it to json
let jsonData = '{"nbf": 1564128888,"exp": 1564132488,"iss": "http://example.com:5002","aud": "http://example.com:5002/resources","http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress": "Micky#gmail.com","http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": "Micky Mouse","amr": ["custom"]}'
let parsedJSON = JSON.parse(jsonData)
console.log(parsedJSON["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"]) // Micky Mouse
console.log(parsedJSON["nbf"]) // 1564128888
console.log(parsedJSON["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"]) // Micky#gmail.com
And then read it like parsedJSON["your key"]. Things on the left sides are property names or keys. You can retrive them by
let jsonData = '{"nbf": 1564128888,"exp": 1564132488,"iss": "http://example.com:5002","aud": "http://example.com:5002/resources","http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress": "Micky#gmail.com","http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": "Micky Mouse","amr": ["custom"]}'
let parsedJSON = JSON.parse(jsonData)
console.log(Object.keys(parsedJSON))
JSON.parse(yourData) - convert JSON to JS
JSON.stringify(yourData) - from JS to JSON
so after JSON.parse you will get JS object and able to get yourData.name
Here you can read:
MDN:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
you can try for example: https://jsonformatter.org/json-parser