Adding an element to JSON notation using Javascript objects - javascript

I wish to add wishlist functionality to a client site using a combination of Javascript and cookies. To achieve this, each item on the site will have a button that the user can click to add the item to their wishlist. The button code is as follows:
<a data-id="5054" data-node="3286" data-type="package" class="wishList">Add to Wishlist</a>
When the button is clicked the following JavaScript is executed:
$('.wishList').click(function () {
var nodeId = $(this).data("node");
var id = $(this).data("id");
var type = $(this).data("type");
var package = new Object();
package.id = id;
package.nodeId = nodeId;
var jsonObject = new Object();
jsonObject.package = package;
var jsonString = JSON.stringify(jsonObject);
console.log(jsonString);
var newObject = new Object();
newObject.id = 8888;
newObject.nodeId = 7777;
var obj = JSON.parse(jsonString);
obj['package'].push(newObject);
console.log(JSON.stringify(obj));
});
This code is derived from this Stack Overflow question and my own knowledge:
Adding a new array element to a JSON object
The aim of the code is to simulate both creating a new JSON notation using Javascript objects as well as parsing the notation back into a Javascript object, adding a new item to the array and then using stringify to convert it back into a string again. My problem is, the push method does not seem to work. When I run this code, I get the following error:
TypeError: obj.package.push is not a function
As this part of the code was taken from the other question, I am at a loss to understand why it is not working in this context as I do not see any comments suggesting that this does not work on the other post.
My aim is to build up the following JSON notation:
{"package":[{"id":"5054","nodeId":"3286"},{"id":"8888","nodeId":"7777"}]}
This will eventually lead to a more complex notation of:
{"package":[{"id":"5054","nodeId":"3286"},{"id":"8888","nodeId":"7777"}], "hotel":[{"id":"3421","nodeId":"1234"},{"id":"8748","nodeId":"2435"}],}
This notation will then be stored as a cookie that will be added to and manipulated using JavaScript and read on the server side with each request using .Net.
My question is, what am I doing wrong here? Why in this case is the .push funcionality not working?
I've created a Fiddle here: http://jsfiddle.net/jezzipin/kdVVK/

As your package property will be a simple list of objects, it needs to be an array.
$('.wishList').click(function () {
var nodeId = $(this).data("node");
var id = $(this).data("id");
var type = $(this).data("type");
var package = [];
package.push({
id: id,
nodeId: nodeId
});
var jsonObject = {};
jsonObject.package = package;
var jsonString = JSON.stringify(jsonObject);
console.log(jsonString);
var newObject = {
id: 8888,
nodeId: 7777
};
var obj = JSON.parse(jsonString);
obj['package'].push(newObject);
console.log(JSON.stringify(obj));
});
updated fiddle

Related

How to get json data with vars in p5.js

I'm building a dictionary word definition search engine which has a #submit button and #word input. I also have a JSON dictionary(Github link). I don't know how to select what word definition to use depending on what the user types.
I have already tried putting the input.value() as a var to the json object query:
var uInVal = input.value();
document.getElementById("p1").innerHTML = words.uInVal)
Can someone help me?
My Code:
var words;
var input;
function setup() {
loadJSON("dictionary.json", gotData);
var button = select('#submit');
button.mousePressed(keyDraw);
input = select('#word');
}
function gotData(data){
words = data;
}
function keyDraw(){
document.getElementById("p1").innerHTML; //This is where the word definition should get printed
}
In the future, please try to work with a simpler example. Something like this would show your problem in a runnable example:
var jsonString = '{"x": 42, "y":100}';
var jsonObject = JSON.parse(jsonString);
This is also easier for you to work with. Now that you have this, I'd google something like "javascript get value from property name" for a ton of results.
But basically, there are two ways to get the value of a property:
var xOne = jsonObject.x;
var xTwo = jsonObject['x'];
console.log(xOne);
console.log(xTwo);
This is what you're trying to do:
var varName = 'x';
var myX = jsonObject.varName;
This won't work, because jsonObject doesn't have any field named varName. Instead, you want to access the x field. To do that, you can use bracket [] notation:
var myX = jsonObject['x'];

How to Create javascript json multidimensional tree from flat data

Hello guys I have a problem creating JSON tree from input form. Imagine you have one section of fields and then dynamically more sections are added. To be more precise, I am talking about switch properties. I just dont know how to add key as new array and then put there more properties with values. Here is the code I am fighting with.
//FIRST section with just basic info about switch
function generateNewSwitchInDB() {
var portInfo = [];
$('#myModal').find('#inputs').find('input').each(function(){
var switchProperty = $(this)[0].id;
portInfo[switchProperty] = $(this)[0].value;
});
//SECOND section dynamically loop through new created sections and grab input id and input value
portInfo.push({'portSlots' : 'portSlot'});
$('#myModal').find('.ports').each(function(){
portInfo[0]['portSlots'][$(this)[0].id] = $(this)[0].id;
$(this).find('input').each(function(){
var placeHolder = $(this)[0].placeholder;
portInfo[0]['portSlots']['0'][placeHolder] = $(this)[0].value;
});
});
console.log(portInfo);
}
What i want to achieve should look like this, but I cant figure out how to push there new key and to that key add properties.
{
'SwitchBasicInfo':{
'location':'Munich',
'vendor':'Cisco',
'hostname':'Switch123',
},
'Slots':{
'slot1':{
'numberOfEthernetPorts':'20',
'numberOfSerialPorts':'50',
'numberOfConsolePorts':'1',
},
'slot2':{
'numberOfEthernetPorts':'50',
'numberOfSerialPorts':'2',
'numberOfConsolePorts':'1',
},
'slot3':{
'numberOfEthernetPorts':'100',
'numberOfSerialPorts':'20',
'numberOfConsolePorts':'1',
},
}
}
Ok, I figured that out, every new level must begin with an array.
First section with basic data
var newSwitchData = new Object();
newSwitchData = {'switchBasicInfo': {}};
newSwitchData.switchBasicInfo['switchProperty'] = $(this)[0].value;
Dynamic sections within foreach loop
newSwitchData.portSlots = {};
newSwitchData.portSlots['slotId'] = {};
newSwitchData.portSlots['slotId']['placeHolder'] = $(this)[0].value;

How to get the "typeof" in JavaScript for a json message

When i try to get the type of an element using the below code it works.
var bodyContent = JSON.parse(response.content);
response.content = typeof bodyContent.CompanyList.Company.Name;
Output response for above was String
Whereas if i try it in the below approach this does not work for the same JSON message. Please help
var bodyContent = JSON.parse(response.content);
var nameHolder = "CompanyList.Company.Name";
response.content = typeof bodyContent[nameHolder];
Output was undefined
That's because it's a nested object, you can't just pass a period delimited name and have it recursively drill down the tree (you'll have to implement that yourself).
It's the difference between
bodyContent["CompanyList"]["Company"]["Name"]; // former
and
bodyContent["CompanyList.Company.Name"]; // latter
There are 2 solutions for this issue.
You have to parse the nameHolder path. Reference: Accessing nested JavaScript objects with string key
or use eval but I'll not write about this since it's not a good practise.
It looks for a property called "CompanyList.Company.Name".
This works:
var bodyContent = JSON.parse(response.content);
var list = "CompanyList";
var company = "Company";
var name = "Name";
response.content = typeof bodyContent[list][company][name];

Google javascript - accessing and renaming numeric object names

I imported json data into google scripts with:
var doc = Utilities.jsonParse(txt);
I can access most of the objects like such...
var date = doc.data1.dateTime;
var playerName = doc.data1.playerName;
var playerId = doc.data1.playerID;
var teamNumber = doc.data2.personal.team;
A bunch of objects I need to access have numbers as object names...
doc.data2.personal.team.87397394.otherdata
doc.data2.personal.team.87397395.otherdata
doc.data2.personal.team.87397396.otherdata
doc.data2.personal.team.87397397.otherdata
...but when I try to read the data with...
var teamId = doc.data2.personal.team.87397394;
... I get an error "Missing ; before statement."
I tried this...
var teamId = doc.data2.personal.team[87397394];
... and get "teamId undefined" in the log.
I also tied this with the same result...
var teamId = doc.data2.personal.team[+'6803761'];
I can read in the names as strings very easily with "For In", but can't get to the objects themselves. Every example I've found so far uses the brackets so I'm stumped what to try next.
Thank you!
Brian
UPDATE
I used this per your suggestions to get the object name into a variable and using the variable in brackets. No error but var test remains "undefined"...
for(var propertyName in doc.data2.personal.team) {
// propertyName is what you want
// you can get the value like this: myObject[propertyName]
Logger.log (propertyNames);
var test = doc.data2.personal.team[propertyName];
}
The log shows the object names, as expected...
87397394
87397395
87397396
87397397
I'm thinking it's a bug in Google's implementation. Here is an example if anyone wants to verify it. test will return undefined...
function myFunction1() {
var txt = UrlFetchApp.fetch("http://www.hersheydigital.com/replays/replays_1.json").getContentText();
var doc = Utilities.jsonParse(txt);
for(var propertyName in doc.datablock_battle_result.vehicles) {
Logger.log (propertyName);
var test = doc.datablock_battle_result.vehicles[propertyName];
}
}
The problem seems to be in the Utitlies.jsonParse. The following works fine
var txt = UrlFetchApp.fetch("http://www.hersheydigital.com/replays/replays_1.json").getContentText();
var doc = JSON.parse(txt);
for(var propertyName in doc.datablock_battle_result.vehicles) {
var vehicle = doc.datablock_battle_result.vehicles[propertyName];
Logger.log('Vehicle id is ' + propertyName);
Logger.log('Vehicle value is ' + JSON.stringify(vehicle));
break;
}

Javascript JSON stringify No Numeric Index to include in Data

i am trying to pass non numeric index values through JSON but am not getting the data.
var ConditionArray = new Array();
ConditionArray[0] = "1";
ConditionArray[1] = "2";
ConditionArray[2] = "3";
ConditionArray['module'] = "Test";
ConditionArray['table'] = "tab_test";
var Data = JSON.stringify(ConditionArray);
When i alert the Data Variable it has the Values 1,2 and 3 but module and table are not included. How can this be added so that the whole string is passed.
EDIT : And what if i have some multidimensional elements also included like
ConditionArray[0] = new Array();
ConditionArray[0] = "11";
JSON structure only recognizes numeric properties of an Array. Anything else is ignored.
You need an Object structure if you want to mix them.
var ConditionArray = new Object();
This would be an better approach:
var values = {
array : ["1", "2", "3"],
module : "Test",
table : "tab_test"
};
var data = JSON.stringify(values);
Since javascript array accepts numeric index only. If you want non numeric index,use Object instead.
var ConditionArray = {};
ConditionArray[0] = "1";
ConditionArray[1] = "2";
ConditionArray[2] = "3";
ConditionArray['module'] = "Test";
ConditionArray['table'] = "tab_test";
var Data = JSON.stringify(ConditionArray);
Here is the working DEMO : http://jsfiddle.net/cUhha/
According to the algorithm for JSON.stringfy (step 4b), only the (numeric) indices of arrays are stringified.
This is because Array does not contain your elements.
When you do this:
ConditionArray['module'] = "Test";
You actually add a property to the ConditionArray, not elements. While JSON.stringify converts to string only elements of the ConditionArray. For example:
var arr = new Array;
arr['str'] = 'string';
console.log(arr.length) //outputs 0
You need to use an Object instead of Array
If you change the first line to
var ConditionArray = new Object();
you will achieve the desired outcome.
If for some reason you cannot convert your array into object, for instance you are working on a big framework or legacy code that you dont want to touch and your job is only to add som feature which requires JSON API use, you should consider using JSON.stringify(json,function(k,v){}) version of the API.
In the function you can now decide what to do with value of key is of a specific type.
this is the way how I solved this problem
Where tblItemsTypeform is array and arrange is de index of the array
:
let itemsData = [];
for(var i = 0; i <= this.tblItemsTypeform.length -1;i++){
let itemsForms = {
arrange: i,
values: this.tblItemsTypeform[i]
}
itemsData.push(itemsForms)
}
And finally use this in a variable to send to api:
var data = JSON.stringify(itemsData)

Categories