Why JSON.parse not working on this string? - javascript

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??

Related

Getting object key and value from objects in a text file

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.

Extract Data Values from JSON ouput

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

Accessing an element of my json response in javascript

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;

Parsing a JSON with Javascript yields undefined

I am hitting a test API I built with jQuery which gives me a JSON.
In my Javascript, I am doing the following:
var myjson = (getData['responseJSON']['results']);
console.log(myjson);
This yields the below results:
{"A":{"0":1,"1":2},"B":{"0":2,"1":3},"C":{"0":3,"1":4}}
I would like to instead just return the values for A, which I assumed would just be like below. But when I do this I get undefined. What am I doing wrong here?
var myjson = (getData['responseJSON']['results']['A']);
console.log(myjson);
var myjson = JSON.parse(getData['responseJSON']['results']);
console.log(myjson['A']);

Parse xml with Jquery and Javascript

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...);
});

Categories