i try to build json structure object dynamically according examples i saw in the net but with no success.
this is the json i try to build:
{
"campaigns": [
{
"campaign_id":,
"profile_id":,
"state":,
"goal":
},
{
"campaign_id":,
"profile_id":,
"state":,
"goal":
}
]
}
and this is the code :
this function called each time there is data to build the campaigns (in the json) element
var campaignsJson ={};
campaignsJson.campaigns =[];
var i = 0;
function buildJson(stateCampaignId,
profile_id,
stateSelectedValue,
dailyImpressionGoalValue,
pacingValue,
segmentGroupTargetsUpdatedataValue,
frequencytypeProfileValue,
frequencysetProfileValue
)
{
campaignsJson.campaigns[i].campaign_id = stateCampaignId;
campaignsJson.campaigns[i].profile_id = profile_id;
campaignsJson.campaigns[i].state = stateSelectedValue;
campaignsJson.campaigns[i].goal = dailyImpressionGoalValue;
i++;
var campaignsJsonstringify = JSON.stringify(campaignsJson);
alert(campaignsJsonstringify);
}
it gives me "cannot set property campaign_id of undefined"
what does it means ?and why ?
Just before
campaignsJson.campaigns[i].campaign_id = stateCampaignId;
add this :
campaignsJson.campaigns[i] = {};
So that there is an object onto which you'll be able to set properties.
Now, please, don't speak of "JSON structure". What you build is a plain standard JavaScript object while JSON is only the string based exchange format.
Related
I have json array from Json object in js like :
let jsonObject = JSON.parse(response);
let jsonArray = jsonObject.items;
When I'm trying to parse it as array using
jsonArray.map((item)=>{
console.warn(item.name); // also I tried with for loop like jsonArray[i].name
})
I got error like TypeError: Cannot read property.
But in jsonArray I have element with key name. Also when I'm trying print as jsonArray[0].name it works fine!
Example of jsonArray (Json objects on jsonArray is not same):
[
{
"name":"SomeNameHere",
"secondKey":"secondValue"
},
{
"type":"typeValue",
"secondType":"typeValue",
},
{
"name":"SomeNameHere",
"secondKey":"secondValue"
},
{
"type":"typeValue",
"secondType":"typeValue",
}
]
If it important I used Mac OS Mojave, and running react-native run-android on my device
viewListArray = jsonArr.map((item) => {
console.warn(item.name);
});
jsonArray.forEach((item) => {
console.warn(item.name);
});
Array.forEach() will loop through an array.
on each second JSON object I don't have property name "name". and I did't check it. Now I'm checking like item.name == undefined?item.name:'';
When I tried to pass a list to the template I got an error.
The list is defined like:
myList: List<Map<String,int[]>>
Now the data of myList is :
[{First Try=[1,0,0,1], Second Try=[1,1,2,2]}, {}]
I use chart.js to show a chart and so I need a int[] as data list.
my view:
#(myList: List[Map[String,Array[Int]]])
var list = #myList;
for(var i=0;i<list.length;i++){
var map = list[i];
for(var key in map){
myFunction(key,map[key]);
}
}
myFunction(string,array){
//I want directly use the array to the chart’s datasets
//others
var myChart = new Chart(chartid, {
type: 'bar',
data: {
labels: [“a”, “b", “c”, ”s”],
datasets: [{
data: array
}]
}
}
But I got error when I try to traversal the List (The error line shown with Chrome debug)
var out = [{First Try=[I#6e37161d, Second Try=[I#5788d8a9}, {}];
// “Uncaught SyntaxError: Invalid or unexpected token”.
I know when directly output array with
System.out.println(array);
in java it will happen with the string like [I#6e37161d, but I don’t know how to deal with it in javascript.How can I use this array?I will be grateful if anyone can help .
Thank you very much.
You can't convert the Java object directly to a Javascript variable like you're attempting to do.
var list = #myList;
That just takes myList.toString() and attempts to set that as a literal Javascript variable. You need to serialize your Java object to JSON first, then you can parse the JSON in Javascript. Like so:
// Java controller code
String myListJson = Json.stringify(Json.toJson(myList));
// Template
#(myListJson: String)
var list = JSON.parse("#myListJson");
I have a below set of code to get the table data in an array and pass the same to servlet through ajax call. But i am getting null. Please someone help me on what my mistake / how to get the required data since i am new to this servlet and web app. So far i tried with some examples given in SO. but i am clueless to get my expected data.
var myTableArray = [];
$("table#itemtable tr").each(function() {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function() { arrayOfThisRow.push($(this).text()); });
myTableArray.push(arrayOfThisRow);
}
});
alert(myTableArray);
$.ajax({
url:"insertmasteritem",
type:"POST",
dataType:'json',
data: {json:myTableArray},
success:function(data){
// codes....
},
});
Servlet code
String[] myJsonData = request.getParameterValues("json[]");
System.out.println("myJsonData.length"+myJsonData.length);
for (int i = 0; i < myJsonData.length; i++) {
String[] innerArray=myJsonData[i].split(",");
System.out.println(myJsonData[i]);
}
Send your Json data like this
$.ajax({
url:"insertmasteritem",
type:"POST",
dataType:'json',
data:myTableArray,
success:function(data){
// codes....
},
});
and In Servlet Class
JSONObject jsonObj= new JSONObject(request.getParameter("myTableArray"));
Iterator it = jsonObj.keys();
while(it.hasNext())
{
String jsonKey = (String)it.next();
String jsonValue = jsonObj.getString(jsonKey);
System.out.println(jsonKey + " --> " + jsonValue );
}
Well, you need to send a properly formatted JSON object (as a string) to the servlet. Possibly the easiest way to do this is to create some javascript objects and fill an array with these objects. The array data should then be
converted to a JSON string (using JSON.stringify). I'm going to hardcode object values (but you will get them from your table)
Javascript code
function generateJson(){
var myObjArr = [];
//you will typically have just one object (e.g. myObj, which you will fill in your ajax table loop
//myObj.v1 = v1_val;
//myObj.v2 = v2_val;
...
//myObjArr[i] = myObj; //
myObj1 = { "v1": "Orange", "v2": "ABC", "v3":10,"v4":"OK" };
myObj2 = { "v1": "Apple", "v2": "XYZ", "v3":25,"v4":"OK" };
myObjArr[0] = myObj1;
myObjArr[1] = myObj2;
var jsonObjStr = JSON.stringify(myObjArr);
//you can now use jsonObjStr to send your data to the servlet
// document.getElementById("json").innerHTML = jsonObjStr;//this is just added for testing purposes
}
The generated JSON
[{"v1":"Orange","v2":"ABC","v3":10,"v4":"OK"},{"v1":"Apple","v2":"XYZ","v3":25,"v4":"OK"}]
As you can see, the json string starts with a [ (which denotes an array). You may have to change this to start with a { (and with a } ) depending on how your JSON parser works ({} denote an object).
For the servlet part, it depends on the actual JSON parser you're using. Try to use some of the suggestions provided by others. I can provide some code using Jackson though, but you will have to add the Jackson library to your classpath.
why you are getting parameter value as JSON[]
String[] myJsonData = request.getParameterValues("json[]");
I have a json like
var obj={
"address":{
"addlin1":"",
"addlin2":""
},
"name":"sam",
"score":[{"maths":"ten",
"science":"two",
"pass":false
}]
}
Now when Iam trying to modify the json iam try an array variable and passing above json to that like
var data=JSON.parse(obj);
var json={};
json['name']=data['name'];
json['address']={};
json['address']['addressline1']=data['address']['addlin1'];
json['address']['addressline2']=data['address']['addlin2'];
json['marks']={};
json['maths']=data['score']['maths'];
For name and address I was able to form the json as i was expecting.But for marks I was unable.May be in obj json score values are in [ ]
So,when i console the json it is in this way
"name":"sam",
"address":{
"addresslin1":"",
"addresslin2":""
},
"score":{}
}
So how can I also read the values inside [] array.
Can someone help me
Thanks
json['maths']=data['score'][0]['maths'];
if you're not sure that data['score'] has any elements you can check prior to reading maths key:
if (data['score'].length) {
json['maths']=data['score'][0]['maths'];
}
data['score'] is an array, so you can't read it like that
json['maths']=data['score']['maths'];
you have to read it like that:
json['maths'] = data['score'][0].maths;
Also, obj is not a JSON, but a JavaScript object. You can use it directly.
json['maths'] = obj['score'][0].maths;
A JSON is a string, like that:
JSON.stringify(obj)
var json = "{"address":{"addlin1":"","addlin2":""},"name":"sam","score":[{"maths":"ten","science":"two","pass":false}]}";
create another json2 to contain score data then assign to json.
for example :
var json={};
json2 = {}
json2[0] = 1;
json2[1] = 2;
json[0] = json2;
I have a mongodb document with the following structure
> db.user.find().limit(1);
{ "_id" : "1", "foo" : { "bars" : [
{
"name" : "bar1"
},
{
"name" : "bar2"
},
], ... }, ... }
I want to add a new property to each bar. I've got my script iterating over the bars array, but I can't get the new property in there, how can I do this?
var users = db.user.find({"foo.bars":{$exists:true}});
users.forEach(function(user) {
user.foo.bars.forEach(function(bar)
{
printjson(bar);
//how can I specify the current 'bar' in this update?
//db.experience.update({_id: user._id}, {$set: {"what goes here?" : "newbarValue"}});
});
});
So says the preacher man:
var users = db.user.find({"foo.bars":{$exists:true}});
users.forEach(function(user) {
var id = user._id;
var foo_bars = user.foo.bars;
var new_foo_bars = [];
for(var i = 0; i < foo_bars.length; i++) {
var foo_bar = foo_bars[i];
foo_bar['newkey'] = 'newvalue';
new_foo_bars.push(foo_bar);
}
db.user.update({"_id":id}, {$set:{"foo.bars":new_foo_bars}});
});
I have noticed that you are scrolling through the array on the client side there in JS.
If you were to form a new "bars" array from the old one then push it in as a whole new value this would mean you only do one DB call and the code is quite elegant.
If MongoDB does not support it normally it is better to just do the work on the client side.
You have to update each element of the nested document individually. Using the positional operator '$' will not work since it will only work on the first match (as documented).