Accessing an element of my json response in javascript - 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;

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.

How can I most easily parse this HTTP response into JSON to then access responseText fields?

I'm trying to parse the plaintext that's returned from this URL -- https://www.cloudflare.com/cdn-cgi/trace -- in order to read the IP address value. This is the code snippet I'm using for the request:
ipAddress = $.get('https://www.cloudflare.com/cdn-cgi/trace', function(data) {
return data;
});
When logged in browser console, the response looks like the following:
I've tried using JSON.stringify(), accessing responseText using ['responseText'], as well as .responseText.. but no luck.
How can this response be parsed so that I can most easily access the ip value from within responseText?
$.get("https://www.cloudflare.com/cdn-cgi/trace", function(data) {
const [ ,ip ] = data.match(new RegExp("ip=" + "(.*)" + "\n"));
console.log(ip);
});
Outputs
"2a01:cb18:362:2200:e90e:fb09:8445:6302"
You can either parse on carriage return or simply look for the ip= in the string or use a regex search it.
If you look at ipAddress.reponseText it's a carriage return delimited string.
so
var myip=ipAddress.responseText.split('\n');
console.log(myip[2]); 'the text ip=192.168.1.10 for example if it's always in the same position.
If it's not in the same position then look through the array to find it.
its return document as response, so i'm not pretty clear about JSON, here some way
const ipAddress = $.get('https://www.cloudflare.com/cdn-cgi/trace', function (data) {
const arr = data.split("\n")
const ip = arr.filter(v => v.includes("ip="))[0]
console.log(ip.split("=")[1])
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

when saving an array of objects as a JSON, I need to use the following format in Sample.txt to not run into parsing errors:

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

Convert ajax String data to array to update ploty data

I am trying to update a jqplot chart dynamically with Ajax requests.
My server is returning a string represtation of the data as such:
"[['Juice',30],['Milk',30],['Water',30]]"
However I need to convert this string into an array of arrays.
Is this the correct approach to update the data and if so what is the best way to convert the string.
$.ajax({
url:'http://localhost',
success:function(plotData){
var data = plotData.split(",");
if(plot){
plot.series[0].data = data;
plot.redraw();
}
},
fail:function(error){
alert('error:'+error);
}
});
This code will convert into a one dimentional array:
0: "[['Helpdesk'"
1: "30]"
2: "['Users'"
3: "30]"
4: "['Auto Generated'"
5: "30]]"
You can use eval("var x= " + plotData) as an alternate solution. There are few dangers in using eval, please go through it before using it.
for convertiong a string u possibly could use this function
var plotData = "[['Juice',30],['Milk',30],['Water',30]]";
function strToArr(str) {
//pattern that checks for '[', ']'
var patt=/[\[\]]/gi;
//we replace the pattern with '' symbol
var tmp = str.replace(patt,'').split(',');
var result = []
for (var i = 0; i < tmp.length; i+=2) {
//now all data is in one array, we have to putt in pairs
result[i] = [ tmp[i], tmp[i+1] ]
}
return result;
}
console.log( strToArr(plotData) );
Format your data correctly
It looks like the response you're getting from the server is supposed to be JSON. But, it isn't valid json, and as such is represented as a string.
The change required is very trivial, This is invalid json:
[['Juice',30],['Milk',30],['Water',30]]
This is valid json:
[["Juice",30],["Milk",30],["Water",30]]
The only difference is the quotes. Changing the response string, may (depending on what you're doing server side) correct things immediately such that plotData is already an array of 3 arrays.
Return the right content type
If you are not already serving the response with correct http headers - ensure the response is served as application/json, this of course is in addition to serving a valid JSON string.
Force interpretation as json
To force jQuery to attempt to parse the response as json - you can set dataType explicitly:
$.ajax({
...
dataType: 'JSON'
...
});
I can't remember how strict this is that may work with no server side modifications.
Use JSON.parse
Alternatively, if you just want to handle the string as-is; you could just use JSON.parse:
input = "[['Juice',30],['Milk',30],['Water',30]]";
jsonString = input.replace(/'/g, '"'); // correct quotes as per point 1
result = JSON.parse(jsonString);
result would then be an array containing 3 arrays.

Categories