Hi i have a Json like below format .I want to replace the value of text:"Sample Text" Sample text with a value from My array in js file.
JSON Format
prx.xdata = {"cc":6,
"symbols":[
{
"id":1,
"title":"news container",
"states":[
{"title":"Default State",
"background":"none",
"data":"[{\"name\":\"text\",\"type\":\"text\",\"lib\":\"common\",\"caption\":\"newsitem1\",
\"text\":\"Sample text\",\"textFont\":\"sans-serif,Helvetica Neue,Arial\",\"textSize\":\"16\",
\"textColor\":\"000000\",\"backgroundColor\":\"none\",\"width\":292,\"height\":257,\"textProperties\":[],
\"textAlign\":\"left\",\"enableShadow\":false,\"autoResize\":false,\"left\":8,
\"top\":21,\"vpos\":\"top\",\"hpos\":\"left\",\"visible\":true,\"id\":\"box-2\",
\"groups\":[],\"zindex\":2001,\"wtype\":\"fixed\",\"htype\":\"fixed\",\"opacity\":\"1\"},
{\"name\":\"text\",
\"type\":\"text\",\"lib\":\"common\",\"caption\":\"news item2\",\"text\":\"Sample text\",\"textFont\":\"sans-serif,Helvetica Neue,
Arial\",\"textSize\":\"16\",\"textColor\":\"000000\",\"backgroundColor\":\"none\",\"width\":301,\"height\":257,\"textProperties\":[],
\"textAlign\":\"left\",\"enableShadow\":false,\"autoResize\":false,\"left\":300,\"top\":21,\"vpos\":\"top\",\"hpos\":\"left\",
\"visible\":true,\"id\":\"box-3\",\"groups\":[],\"zindex\":2002,\"wtype\":\"fixed\",\"htype\":\"fixed\",\"opacity\":\"1\"},
{\"name\":\"text\",\"type\":\"text\",\"lib\":\"common\",\"caption\":\"news item3\",\"text\":\"Sample text\",
\"textFont\":\"sans-serif,Helvetica Neue,Arial\",\"textSize\":\"16\",\"textColor\":\"000000\",
\"backgroundColor\":\"none\",\"width\":292,\"height\":257,\"textProperties\":[],\"textAlign\":\"left\",
\"enableShadow\":false,\"autoResize\":false,\"left\":601,\"top\":21,\"vpos\":\"top\",\"hpos\":\"left\",
\"visible\":true,\"id\":\"box-4\",\"groups\":[],\"zindex\":2003,\"wtype\":\"fixed\",
\"htype\":\"fixed\",\"opacity\":\"1\"},
{\"name\":\"text\",\"type\":\"text\",
\"lib\":\"common\",\"caption\":\"news item4\",\"text\":\"Sample text\",
\"textFont\":\"sans-serif,Helvetica Neue,Arial\",\"textSize\":\"16\",\"textColor\":\"000000\",
\"backgroundColor\":\"none\",\"width\":298,\"height\":257,\"textProperties\":[],
\"textAlign\":\"left\",\"enableShadow\":false,\"autoResize\":false,\"left\":901,\"top\":21,
\"vpos\":\"top\",\"hpos\":\"left\",\"visible\":true,\"id\":\"box-5\",\"groups\":[],\"zindex\":2004,\"wtype\":\"fixed\",
\"htype\":\"fixed\",\"opacity\":\"1\"}]",
"history":[],"dimensions":["1200","300"],"id":"a8d0d79e-1921-4f7e-a229-75e5b1602881"
}]
,"sort":0,
"customguides":{"horizontal":[],"vertical":[]},
"grid":{"col_number":3,"col_width":80,"gutter_width":20,"margins":10}
}]
};
prx.xdata_str = JSON.stringify(prx.xdata);
I want to replace the value of "Sample text " in this path
symbols[0].states[0].data[0].text with value from News array.
Problem is here
symbols[0].states[0].data this data is another JSON ,so am not able to parse that data.
Please check my Js code
function yourJsFunction(arr){
var b=arr.toString().split(',');
var News =new Array();
News=b;
var jsondata = JSON.parse(prx.xdata);
//alert(jsondata.symbols[0].states[0].data);
var data=new Array();
data=jsondata.symbols[0].states[0].data;
// alert(data);
var newData=JSON.parse(data);
newData[0].text=News[0];
newData[1].text=News[1];
newData[2].text=News[2];
newData[3].text=News[3];
alert(newData[0].text);
//This alert showing my updated json.But when i click ok in alert the webview showing previous Json
jsondata.symbols[0].states[0].data= JSON.stringify(newData);
prx.xdata = JSON.stringify(jsondata);
for(var i=0;i<arr.length;i++){
// document.write(arr[i]);
}
}
var x = "{a: 'a', b: 'b'}" this is an json string
var o = eval('"' + x + '"') o is json object, parsed.
Related
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[]");
var data = '[{"type":"product","id":1,"label":"Size","placeholder":"Select Size","description":"","defaultValue"
:{"text":"Size30","price":"20"},"choices":[{"text":"Size30","price":"20","isSelected":"true"},{"text"
:"Size32","price":"22","isSelected":false},{"text":"Size34","price":"28","isSelected":false}],"conditionalLogic"
:""},{"type":"product","id":2,"label":"Color","placeholder":"Select Color","description":"","defaultValue"
:{"text":"Black","price":"10"},"choices":[{"text":"Black","price":"10","isSelected":"true"},{"text"
:"Green","price":"22","isSelected":false},{"text":"Red","price":"28","isSelected":false}],"conditionalLogic"
:""},{"type":"product","id":3,"label":"Rise","placeholder":"Select Rise","description":"","defaultValue"
:{"text":"Low","price":"8"},"choices":[{"text":"High","price":"12","isSelected":"true"},{"text"
:"Low","price":"8","isSelected":false}],"conditionalLogic"
:""}]';
Here I have posted my JSON data. I want to get all the defaultValue in JSON/Array format. My output should be like-
defaultValues:['Size30','Black','Low']
How to manage that in the foreach loop?
my code :
var otherSelectedOption;
angular.forEach(data, function(optionValue, optionKey) {
if (optionValue.defaultValue.text) {
otherSelectedOption = (optionValue.defaultValue.text);
}
selectedOption = {defaultValues: otherSelectedOption};
console.log(selectedOption);
});
Your JSON is not valid, since objects are not separated by comma ,
Suppose this is the JSON
var obj = '[{"type":"product","id":1,"label":"Size","placeholder":"Select Size","description":"","defaultValue"
:{"text":"Size30","price":"20"},"choices":[{"text":"Size30","price":"20","isSelected":"true"},{"text"
:"Size32","price":"22","isSelected":false},{"text":"Size34","price":"28","isSelected":false}],"conditionalLogic"
:""},{"type":"product","id":2,"label":"Color","placeholder":"Select Color","description":"","defaultValue"
:{"text":"Black","price":"10"},"choices":[{"text":"Black","price":"10","isSelected":"true"},{"text"
:"Green","price":"22","isSelected":false},{"text":"Red","price":"28","isSelected":false}],"conditionalLogic"
:""},{"type":"product","id":3,"label":"Rise","placeholder":"Select Rise","description":"","defaultValue"
:{"text":"Low","price":"8"},"choices":[{"text":"High","price":"12","isSelected":"true"},{"text"
:"Low","price":"8","isSelected":false}],"conditionalLogic"
:""}]';
try
var arr = JSON.parse(obj).map( function(item){
return item.defaultValue;
});
Hi Friends I am trying to merge two json arrays i have tried concat and merge method but it's not giving the correct output please suggest something...
var set_image=[{"id":"aerobics"},{"id":"kick boxing"}]
var item_json=[{"id":"net ball"},{"id":"floor ball"}]
Merged Array
var finalArray =[{"id":"aerobics"},{"id":"kick boxing"},{"id":"net ball"},{"id":"floor ball"}]
Here is my javascript
var item = JSON.parse(localStorage.getItem("test"));
var item_json = JSON.stringify(item) ;
var page= <?php echo $json_value; ?>;
var set_image=JSON.stringify(page) ;
//var image=set_image.concat(item_json);
var image= $.concat(set_image, item_json)
window.location.href = "modal.php?ids=" + image;
Convert the merged array to json string after that encode it using encodeURIComponent() to pass in url
var set_image=[{"id":"aerobics"},{"id":"kick boxing"}]
var item_json=[{"id":"net ball"},{"id":"floor ball"}]
var arr= set_image.concat(item_json);
window.location.href = "modal.php?ids=" + encodeURIComponent(JSON.stringify(arr));
concat() is exactly what you need, however your usage of it is incorrect:
var set_image = [{ "id": "aerobics" },{ "id": "kick boxing" }]
var item_json = [{ "id": "net ball" },{ "id": "floor ball" }]
var image = set_image.concat(item_json);
Working example
Also note that your final line appending the image array to a string will not have the desired effect as it will just append [object Object] multiple times. I would guess you instead want to loop through the array and append each id value individually.
I am dynamically creating a row using javascript, here is the code below:
var row2 = "<tr><td><a href='#editModal' class='modal_trigger' data-info="+name+" data-toggle='modal'>Edit</a></td></tr>";
The var here is a JSON object. This is later passed onto the modal when a user clicks it and values can be retrieved. However, simply declaring var like I have done above sets data-info=[Object object].
The content of the JSON variable is:
Object
name: "Test 8"
created_at: "2015-06-10 16:54:45"
id: 128
updated_at: "2015-06-10 16:54:45"
__proto__: Object
Is there a way around it?
Some advice here:
Don't use var as a variable name, even in examples (real code won't even compile)
Please, make sure you understand what JSON is, because Javascript object != JSON. Clearly var is a JS object in this case.
Said that, you can transform any JS object that does not contain functions into a JSON string with JSON.stringify(variable):
UPDATE: This is what I mean:
var row2 = '<tr><td><a href="#editModal" class="modal_trigger" data-info="'+
name+'" data-toggle="modal">Edit</a></td></tr>';
(Note the changes using quotation marks)
If you get [object Object] then it is not a JSON, is an Object.
JSON is a string containing an object serialized, and it is used as a lightweight data-interchange format.
Try serializing the object to JSON
"...data-info=" + JSON.stringify(myVar||null) + " data..."
Here I added coercion to null to prevent an error when the variable contains no data.
please Use JSON.stringify(yourVar).
var row2 = "<tr><td><a href='#editModal' class='modal_trigger' data-info="+JSON.stringify(yourVar)+" data-toggle='modal'>Edit</a></td></tr>";
Store your name variables in some mapping or array, store the id or the index in your row, and use this to fetch it back later :
// using a mapping :
var infoMapping = {};
function createRow (name) {
// this will work if 'id' is a key which identifies the object
infoMapping[name.id] = name;
var row2 = "<tr><td><a href='#editModal' ... data-infoid="+name.id+" ... ";
// etc ...
}
function editModal (nRow) {
var infoid = $(nRow).attr('data-infoid');
var name = infoMapping[infoid];
// use name ...
}
var x = {a:10, b:20};
var html = "<div data-info='" + JSON.stringify(x) + "'></div>";
Result is
"<div data-info='{"a":10,"b":20}'></div>"
I need only the values .how to get value from these json
-wafer,
-Compound Chocolate,
-Praline Chcolate
etc.....
In this a main problem is "subcategory" and its value is taken from database its change according to database
[{"subcategory":"Wafer"},{"subcategory":"Compound Chocolate"},{"subcategory":"Praline Chcolate"},{"subcategory":"Cookies"},{"subcategory":"Toffee"},{"subcategory":"Eclair"},{"subcategory":"Fruit Chews"}]
each json has a value like subcategory
Fiddle: http://jsfiddle.net/KGms7/
var str = '[{"subcategory":"Wafer"},{"subcategory":"Compound Chocolate"},{"subcategory":"Praline Chcolate"},{"subcategory":"Cookies"},{"subcategory":"Toffee"},{"subcategory":"Eclair"},{"subcategory":"Fruit Chews"}]';
var jsn = JSON.parse(str);
var arr = [];
for(var i in jsn) {
arr.push(jsn[i].subcategory);
}
alert(arr);