I would like to parse the following xml flow :
<telhdl:leg>
<tel:deviceId>82085625</tel:deviceId>
<tel:media>AUDIO</tel:media>
<tel:state>ACTIVE</tel:state>
<tel:capabilities>
<tel:drop>true</tel:drop>
<tel:hold>true</tel:hold>
<tel:mute>true</tel:mute>
<tel:sendDtmf>true</tel:sendDtmf>
</tel:capabilities>
</telhdl:leg>
<telhdl:leg>
<tel:deviceId>82085625</tel:deviceId>
<tel:media>VIDEO</tel:media>
<tel:state>ACTIVE</tel:state>
<tel:muted>true</tel:muted>-
<tel:capabilities>
<tel:drop>true</tel:drop>
<tel:unMute>true</tel:unMute>
</tel:capabilities>
</telhdl:leg>
As you can see, there is 2 groups of leg, but in one of them there is an attributes which is not present in the other (muted) for example.
I have tried to parse it using this code :
$(xmlDoc).find('telhdl\\\\:deviceId,deviceId'); with $(xmlDoc) is the document node.
It works fine, but i don't know how to parse correctly this file to have as result an array which contain information of the 2 legs block.
The question is more : How to have clerary a result of the parsing ?
This should do the trick:
$(xmlDoc).find("telhdl").each(function() {
var deviceId = $(this).find("deviceId").text();
var media = $(this).find("media").text();
....etc....
var array = new Array(deviceId,media,...etc...);
});
Related
I'm using fetch to get visemes from amazon polly as a text file and trying to get the value of each object key time and value key but every time I try to it gives me an undefined error and when I tried using a console.log(out[i]); it just gave me the very first quote in the curly brackets. I even tried adding a JSON.parse(out) to my code but It gave me an Uncaught (in promise) SyntaxError: Unexpected token { in JSON at position 39 error. If you need to see my source code I've attached it below. I've also attached links to this question one that shows the contents of my text file and another that shows the error I got before using the JSON.parse. I hope it helps.
var viseme = 'value';
var time = 'time';
var bracket = '}';
var jsonIndex = -1;
var itemHTML = '';
var number = '4';
fetch(url)
.then(res => res.text())
.then((out) => {
console.log("Checkout this JSON!", out);
console.log(out.substring(27, 37));
var jsonParsed = JSON.parse(out);
for(var i of Array(12).keys()) {
console.log(out[1]);
var anotherResJson = out[i]['#value'];
console.log("jsonParsed[",i,"][#value]:",anotherResJson);
}
})
.catch(error => {
throw error
});
The contents of your file, from what I see in the screenshot, does not appear to be valid JSON. What I am seeing is several individual objects with double-quotes around the values and keys, but they are separated by newlines. This is not valid JSON and will not parse-- run the below snippet with the console open:
const notActuallyJson = '{ "Batgirl": "Barbara Gordon" }\n{ "Supergirl": "Kara Zor-El" }';
console.log(notActuallyJson);
const parsed = JSON.parse(notActuallyJson);
console.log(parsed);
If you are looking for a data structure similar to this that is valid JSON, you want an array ([]) in which these objects are comma-separated:
const validJson = '[\n{ "Batgirl": "Barbara Gordon" },\n{ "Supergirl": "Kara Zor-El" }\n]';
console.log(validJson);
const parsed = JSON.parse(validJson);
console.log(parsed);
UPDATE
Converting the file contents to JSON
It is hard to know exactly the situation with your file contents because you haven't shared them as text-- you've only shared them as an image. However, if my hunch is correct and they are just valid JSON objects separated with newlines, you could wrap them with brackets and separate them with commas like so:
const notActuallyJson = '{ "Batgirl": "Barbara Gordon" }\n{ "Supergirl": "Kara Zor-El" }';
const convertedToActualJson = `[${notActuallyJson.split('\n').join(',')}]`;
console.log(convertedToActualJson);
const parsed = JSON.parse(convertedToActualJson);
console.log(parsed);
If your file contents does not fit that description, then you'll need a more customized solution, which you should probably post in a separate question as it is diverging quite a bit from the original post.
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 response with two jsons, exactly like this -
{
"redirectUrl": "http:\/\/lumoslocal.heymath.com"
},
{
"status": "SUCCESS"
}
I need to redirect on getting the response to the redirectUrl. Something like window.location.href = response.redirectUrl. But it's not working. Possibly because of two json in my response. How do I use the 'redirectUrl' of my first json?
My understanding (from the OP's comments) is that the response is coming back as a string like this: authResp = '{"redirectUrl":"http:\/\/lumoslocal.heymath.com"}, {"status":"SUCCESS"}'
Technically this is not valid JSON as one big chunk, you'll get an error (test it out below)
JSON.parse('{"redirectUrl":"http:\/\/lumoslocal.heymath.com"}, {"status":"SUCCESS"}')
To successfully parse the data (and ultimately get the redirectUrl data), follow these steps:
split the string with a comma "," character
parse the "first JSON element"
redirect to extracted redirectUrl
Here's the code for each step:
authResp = '{"redirectUrl":"http:\/\/lumoslocal.heymath.com"}, {"status":"SUCCESS"}';
// 1. split the string with a comma character:
let authArr = authResp.split(',');
// 2. parse the first JSON element:
let redirectObj = JSON.parse(authArr[0]);
// 3. redirect to extracted redirectUrl
window.location.href = redirectObj.redirectUrl;
Or, if you want to parse the entire string into an array of JSON objects you can do this:
authResp = '{"redirectUrl":"http:\/\/lumoslocal.heymath.com"}, {"status":"SUCCESS"}';
// create array of json strings, then parse each into separate array elements
authArr = authResp.split(',').map(e => JSON.parse(e));
// Finally, follow #JackBashford's code:
window.location.href = authArr.find(e => e.redirectUrl).redirectUrl;
If your two responses are in an array, it's simple, even if they're unordered:
var myJSON = [{"redirectUrl": "http:\/\/lumoslocal.heymath.com"}, {"status": "SUCCESS"}];
window.location.href = myJSON.find(e => e.redirectURL).redirectURL;
Hi guys Im trying to print a list of scores saved within a database, ive got the data as JSON data (see below)
I am trying to print all each object within the "Scores" array using the following code
function showScores() {
var ourRequest = new XMLHttpRequest();
var x, i = "";
ourRequest.open('GET', '/allScores');
ourRequest.onload = function() {
var ourData = JSON.parse(ourRequest.responseText);
for (i in ourData.scores) {
x += ourData.scores[i] + "<br>";
}
document.getElementById("scoresList").innerHTML = x;
};
ourRequest.send();
}
However it is printing out the following
Any help with this is greatly appreciated, thanks guys
This line tries to append a raw object to your HTML string:
x += ourData.scores[i]
Javascript can’t magically parse this into HTML for you, so it just outputs [object Object].
You need to build a string from the individual parts of this object and print that instead. For example:
Note that you should not use for ... in with an array
ourData.scores.forEach(function (score) {
x += `<p>[H] ${score.Home_Team} <b>${score.Home_Score}</b> - <b>${score.Away_Score}</b> ${score.Away_Team} [A]</p>`;
});
Which would output something like this for each score:
[H] Arsenal 2 - 2 Newcastle [A]
Be sure to set x = "" before the loop otherwise the string will still start with undefined.
In case you’re interested: there are more succinct ways of writing this loop. Using Array.map() for instance:
let x = ourData.scores.map(score => {
return `<p>[H] ${score.Home_Team} <b>${score.Home_Score}</b> - <b>${score.Away_Score}</b> ${score.Away_Team} [A]</p>`;
}).join();
This expression does not require initialization of x beforehand.
you can create the elements as string and you can join the entire array and assign it to the innerHTML, as shown below.
You can change the structure, here for example i had made to ul , li you can create table or whatever format.
Note if you want to just append it, since the object you can't directly append it using JSON.stringify which will convert your object into string.
I hope this will solve your issue. Please let me know if any other issue you are facing.
var jsonObj = {scores: [{"Away_Score": 2, "Away_Team": "Newcastle", "Home_Score": 2, "Home_Team": "Arsenal"}, {"Away_Score": 2, "Away_Team": "Napoli", "Home_Score": 4, "Home_Team": "Liverpool"}]}
var html = jsonObj.scores.map(o => {
return `<ul><li>${o.Away_Team}</li><li>${o.Away_Score}</li><li>${o.Home_Team}</li><li>${o.Home_Score}</li></ul>`
})
document.getElementById("todaysData").innerHTML = html.join("")
<div id="todaysData">
</div>
This is an object :-
var query = {id : "1"};
I encoded it : encodeURIComponent(JSON.stringify(query))
and got result : "%7B%22id%22%3A%221%22%7D"
I decoded it and store in lets say dquery..
var dqeury = decodeURIComponent("%7B%22id%22%3A%221%22%7D")
when i print JSON.parse(dqeury) // it worked, here dqeury = "{"id":"1"}"
but the same thing when i done on node api, JSON.parse will throw an error. when i console the dquery there i get exactly same as before.
How should i parse this??