Getting object key and value from objects in a text file - javascript

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.

Related

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

How do I set multiple values of a JSON object?

So I've been working on this project but I'm stuck because I can't figure out how I should go about setting the other values of this new JSON object. So basically on the front end I have this:
HTML page view. The 'cat4' ID is the new object I tried to create, and illustrates the error I'm trying to fix. The problem is that I'm having trouble setting the LIMIT value of newly created objects (or multiple values at all). Here is the code where the object is created:
function sendCat()
{
window.clearTimeout(timeoutID);
var newCat = document.getElementById("newCat").value
var lim = document.getElementById("limit").value
var data;
data = "cat=" + newCat + ", limit=" + lim;
var jData = JSON.stringify(data);
makeRec("POST", "/cats", 201, poller, data);
document.getElementById("newCat").value = "Name";
document.getElementById("limit").value = "0";
}
In particular I've been playing around with the line data = "cat=" + newCat + ", limit=" + lim; but no combination of things I try has worked so far. Is there a way I can modify this line so that when the data is sent it will work? I find it odd that the line of code works but only for setting one part of the object.
The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
MDN
I think this is what you want:
const newCat = 'Meow';
const newLimit = 5;
const data = {
cat: newCat,
limit: newLimit
}
console.log(JSON.stringify(data));
What you're referring to as a 'JSON object' is actually just a javascript object, you can make one using object literal syntax. An object literal with multiple properties looks like this:
var data = {
cat: newCat,
limit: lim
};
makeRec("POST", "/cats", 201, poller, JSON.stringify(data));
assuming the fifth parameter to makeRec is supposed to be the POST request body as stringified JSON, as your code seems to imply

REST Firebase request via qwest

i have a realtime database from firebase with 9386 datasets in it (but that might change in the future)
thats why i want to know whats the "key" of the last event.
thats how i'm currently trying to get it to know: (with npm module qwest)
let order = "\u0022\u0024key\u0022";
let dbUrl = "https://example.firebaseio.com/users.json?limitToLast=1&orderBy=";
let end;
qwest.get(dbUrl + order)
.then(function(xhr, response) {
console.log(response);
end = response[9386]["username"];
console.log(end);
});
first question: why do i have to escape the quotation marks and the dollarsign?
second question: how can i get the "key" of the last item i'm checking for in the json (limitToLast=1).
json response looks like this:
{"9386":
{
"fromListA":"1",
"fromListB":"0",
"id":"9939",
"lastChecked":"2019-05-09 03:18:05",
"userid":"123456789",
"username":"username"
}
}
and i want to get the "9386" in a variabel.
Since you chose to use " to limit the dbUrl string, you can't use " inside that string's value without escaping it. A simpler way to define the string is to use ' to delimit it:
let dbUrl = 'https://example.firebaseio.com/users.json?limitToLast=1&orderBy="$key"';
To get the key of the object, use something like:
Object.keys(response)[0]
var response = {"9386":
{
"fromListA":"1",
"fromListB":"0",
"id":"9939",
"lastChecked":"2019-05-09 03:18:05",
"userid":"123456789",
"username":"username"
}
}
console.log(Object.keys(response)[0]);

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;

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

Categories