I've been trying to work on this project to get better at coding for about half and a month now and I've come across a problem where JSON doesn't really behave the way I want it to. When I try reading a part of a JSON object, it almost always shows 'undefined' as a result.
This is the code, where I store my JSON into a cookie:
var basket = '{ "basket":['+'{ "id": 0, "data-id": 3, "amount": 1 }'+'] }';
document.cookie = 'basket='+JSON.parse(basket)+'; max-age="604800"; path=/';
I read it with:
var basket = getCookie('basket');
for(var i in basket) {
alert(basket[i]);
}
This is the last approach I've tried, this one returns the '{' (i.e. the first character of the JSON when I define it), meaning it behaves as if it were a string, right? In cases, where I've tried to read it with just alert(basket[0]) or alert(basket.basket[0].id) or anything (I've tried countless combinations) it almost always returns 'undefined' with the exception of only returning a part of a string.
Any ideas?
Declare basket object and while saving into cookie use JSON.stringify() method to save it; and when you extract it from cookie use JSON.parse() method to convert it back from string to object.
let basket = {basket:[{id: 0, dataId: 3, amount: 1 }] };
document.cookie = 'basket='+JSON.stringify(basket)+'; max-age="604800"; path=/';
function getBasketFromCookie() {
const basketValue = document.cookie
.split('; ')
.find(row => row.startsWith('basket='))
.split('=')[1];
const basketObj = JSON.parse(basketValue);
return basketObj;
}
const basketObj = getBasketFromCookie();
// print basket object
for (let key in basketObj) {
console.log(basket[key]);
}
console output:
Related
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
I'm trying to load some JSON data from a JSON file and carrying out some data manipulation on it for an app I'm trying to build. However, when looping through the data, I'm getting an undefined error which makes it seem that property is missing from the JSON object when I use a looping variable to access the objects. However, when I index the JSON array with a hardcoded number, the property loads fine. I am wondering if someone can help me out with this. I've attached an example of the code and the JSON to this.
I have tried stringifying the JSON and parsing it again and tried both accessing the JSON using square brackets as well as the full stop and they all lead to the same result.
Code to access:
import ontology from '../../data/ontology.json'
const totalAnswerList = ontology.answers
for (var i = 0; i <= totalAnswerList.length; i++) {
var wordID = totalAnswerList[i] // wordID.id returns undefined
var wordID2 = totalAnswerList[0] // wordID2.id works
alert(JSON.stringify(wordID) + JSON.stringify(wordID2) + '\nWord ID hardcoded: ' + wordID2.id)
}
//ontology.json
{
"answers": [
{
"id": "examination",
"category_id": "examination",
"synonyms": ["examination"]
}, ...
], ...
}
The code you provided works as expected, but the issue is the last element is undefined because of your for loop constraints. You likely want i < totalAnswerList.length and not <=. Because if the array is 5 elements long, you want to loop through 0,1,2,3,4 (and not 5, which will be undefined).
import ontology from "./ontology.json";
const totalAnswerList = ontology.answers;
for (var i = 0; i < totalAnswerList.length; i++) {
// ...
}
I got the following obj that I use to store setting parameters. It holds default values I wanna make the properties of this obj be overwritten by a JSON that comes in via POST request. Sure, I can convert every string value from the JSON indivually and assign it to the corresponing property, however, whats a good practise for that?
const moth_eng = require('./fractioning_model_v1.1.js');
// in ./fractioning_model_v1.1.js set default values
var settings = {
i: 1,
rev_share: 0.2,
parent_level_share: 0.45,
d: 2,
get user_pool_share () {return this.i - this.rev_share;},
get remaining_levels_pool () {return this.user_pool_share - this.parent_level_share;},
};
//main.js
app.post('/fractobj', function (req, res) {
logger.log("info", "/fractobj requested - post")
let obj = req.body;
moth_eng.set_sttngs(obj);
res.send(moth_eng.getFractions(10));
});
// in ./fractioning_model_v1.1.js
function setSettings(obj){
Object.assign(settings, obj);
}
My Problem is, that the Object.assign() does assign the values as strings, since the values of the JSON are string and I find it uncool to individually convert those values for each value.
Whats a proper way to solve this problem in the big picture?
I'm working with the twitter API and I'm hitting a really confusing issue.
I have the following script:
const Twitter = require('twitter-api-stream')
const twitterCredentials = require('./credentials').twitter
const twitterApi = new Twitter(twitterCredentials.consumerKey, twitterCredentials.consumerSecret, function(){
console.log(arguments)
})
twitterApi.getUsersTweets('everycolorbot', 1, twitterCredentials.accessToken, twitterCredentials.accessTokenSecret, (error, result) => {
if (error) {
console.error(error)
}
if (result) {
console.log(result) // outputs an array of json objects
console.log(result.length) //outputs 3506 for some reason (it's only an array of 1)
console.log(result[0]) // outputs a opening bracket ('[')
console.log(result[0].text) // outputs undefined
}
})
Which is calling the following function to interact with twitter:
TwitterApi.prototype.getUsersTweets = function (screenName, statusCount, userAccessToken, userRefreshToken,cb ) {
var count = statusCount || 10;
var screenName = screenName || "";
_oauth.get(
"https://api.twitter.com/1.1/statuses/user_timeline.json?count=" + count + "&screen_name=" + screenName
, userAccessToken
, userRefreshToken
, cb
);
};
It seems like I'm getting the result I want. When I log the result itself I get the following output:
[
{
"created_at": "Thu Sep 01 13:31:23 +0000 2016",
"id": 771339671632838656,
"id_str": "771339671632838656",
"text": "0xe07732",
"truncated": false,
...
}
]
Which is great, an array of the tweets limited to 1 tweet.
The problem I'm running into is when I try to access this array.
console.log(result.length) //outputs 3506 for some reason (it's only an array of 1)
console.log(result[0]) // outputs a opening bracket ('[')
console.log(result[0].text) // outputs undefined
I read back through the api docs for the user_timeline but unless I'm completely missing it I'm not seeing any mention of special output.
Any ideas?
Update
Thanks #nicematt for pointing out that answer.
Just to elaborate on the solution, I updated my code to this and now I'm getting the result I want:
if (result) {
let tweet = JSON.parse(result)[0] // parses the json and returns the first index
console.log(tweet.text) // outputs '0xe07732'
}
Thanks for the help!
Result is a String and you're indexing it (result[0] (whereas 0 is converted to a string), is almost identical to result.charAt(0) though), this is why result[0] is equal to "["–because it's the first character specified in. You forgot to parse the result as JSON data.
JSON.parse(result).length // probably 1
And result.text is undefined since result (a string) is like an Object (but isn't instanceof) and allow lookups and getters to happen in itself.
I'd show the difference between str[0] and str.charAt(0), too:
str[0] // same as str['0'], but a getter. 0 converts to
// string (because every key of an object
// is string in ECMAScript)
str.charAt(0) // get/lookup String#charAt, call it
// without new `this` context and with arguments list: 0
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...