how to filter json object data? - javascript

Input of Json Object:
{"data":[
{"itemID":100,"Testcase1":"aaa","status":"Active"},
{"itemID":100,"Testcase1":"bbb","status":"No"},
{"itemID":100,"Testcase1":"ccc","status":"Active"},
{"itemID":101,"Testcase1":"zzz","status":"Active"}
]}
Expected Output of Json Object:
[{
"itemID":"100",
"Testcase1":"aaa",
"Testcase1":"bbb",
"Testcase1":"ccc",
"status":"Active",
"status":"No",
"status":"Active"
},
{
"itemID":"101",
"Testcase1":"zzz",
"status":"Active"
}]
anybody help me?

may be this helps you. This is not the correct way. Because duplicate key is not allowed in object. whatever as it your request. I have create a string of your required format.
please checkit FIDDLE
var dataVal={"data":[
{"itemID":100,"Testcase1":"aaa","status":"Active"},
{"itemID":100,"Testcase1":"bbb","status":"No"},
{"itemID":100,"Testcase1":"ccc","status":"Active"},
{"itemID":101,"Testcase1":"zzz","status":"Active"}
]};
var arrayVal = dataVal.data;
var DistinctID=[];
var resultStr="";
for (var elements in arrayVal){
if($.inArray(arrayVal[elements].itemID, DistinctID) == -1){
DistinctID.push(arrayVal[elements].itemID)
}
}
for (var items in DistinctID){
resultStr +='{"itemID":"'+DistinctID[items]+'",';
for (var elements in arrayVal){
if(arrayVal[elements].itemID==DistinctID[items]){
resultStr +='"Testcase1":"'+arrayVal[elements].Testcase1+'",';
resultStr +='"status":"'+arrayVal[elements].status+'",';
}
}
resultStr = resultStr.substring(0, resultStr.length - 1);
resultStr= resultStr+'},';
}
resultStr = resultStr.substring(0, resultStr.length - 1);
resultStr='['+resultStr+']';
alert((resultStr));

Assuming your "JSON Object" is a string, you can call JSON.parse() on it:
var data = '{"data":[{ ... }]}';
var parsed = JSON.parse(data);
This will give you data in the following structure:
Your expected output isn't a valid object. Object keys must be unique. An object cannot have three Testcase1 keys or three status keys.

You just have to extract objects from data object ?
Ok then, a pure JS solution :
var obj = {"data":[{"itemID":100,"Testcase1":"aaa","status":"Active"},
{"itemID":100,"Testcase1":"bbb","status":"No"},{"itemID":100,"Testcase1":"ccc","status":"Active"},
{"itemID":101,"Testcase1":"zzz","status":"Active"}]};
var newArray = [];
for( var i = 0; i < obj['data'].length; i++) {
newArray.push(obj['data'][i]);
}
And a live demo of that : http://jsfiddle.net/seLwmbyp/1/ (see the console for the result) > [Object, Object, Object, Object]

Related

Getting null in when trying to get array in servlet

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[]");

How to get JSON object in array?

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;
});

How can I omit the property names of my json and just display the values?

I wrote a small api to pull nutrition info from public diaries on MyFitnessPal. I'm pulling this information into a Google Sheet using the ImportJSON.gs found here: https://gist.github.com/paulgambill/cacd19da95a1421d3164
What I get is a two row result:
Calories Protein Fat Carbs
2458 196 82 234
My returned json looks like this:
{"Calories":"1738","Protein":"140","Fat":"78","Carbs":"119"}
I want just the numbers and not the property names. I don't want to alter the json to just return a string array, but since this is for personal usage, I will if necessary! Any ideas?
var o = {"Calories":"1738","Protein":"140","Fat":"78","Carbs":"119"}
var values = values(o); //gives you an array of values
Obviously you know how to retrieve the JSON. Just loop through the object:
function convert() {
var myJson = {"Calories":"1738","Protein":"140","Fat":"78","Carbs":"119"};
var thisKey;
var thisValue;
var newArray = [];
for (var key in myJson) {
thisKey = key;
thisValue = myJson[thisKey];
newArray.push(thisValue);
};
return newArray;
};
This creates an array of just the values.
returns: [1738, 140, 78, 119]
Simply push each value into a new array:
var values = [];
for (var i in myJson){
values.push(myJson[i])
}

Javascript: How to parse a json array without knowing the key name?

I want to parse the following json:
{"key_410441":{"hashId":"hash123","tube_id":"4accdefk31"}}
Where key_410441 is the entry's name representing the object's value, and the following array is the object's data.
How can I retrieve it's value?
function defined(json) {
for (var i in json) {
var objId = json[i]. ????
}
}
Like Robo Robok said, use Object.keys(object)
if your json look like {"key_410441":{"hashId":"hash123","tube_id":"4accdefk31"}}
function defined(json) {
var hashId = json[Object.keys(json)[0]].hashId
var tube_id = json[Object.keys(json)[0]].tube_id
}
}
you can use shortcut json[Object.keys(json)] because you have olny one object
key_410441
Object keys are returned in form of an array by Object.keys(object)
I suppose you are using jquery and ajax to get a json from an external file. Then the piece of code would be:-
$.getJSON("aa.json", function(data) {
var obj = Object.keys(data),
json = data[obj];
for(var s in json) {
console.log(json[s]);
}
});

Ordered JSONObject

I have a servlet which talks with the database then returns a list of ordered (ORDER BY time) objects. At the servlet part, I have
//access DB, returns a list of User objects, ordered
ArrayList users = MySQLDatabaseManager.selectUsers();
//construct response
JSONObject jsonResponse = new JSONObject();
int key = 0;
for(User user:users){
log("Retrieve User " + user.toString());
JSONObject jsonObj = new JSONObject();
jsonObj.put("name", user.getName());
jsonObj.put("time", user.getTime());
jsonResponse.put(key, jsonObj);
key++;
}
//write out
out.print(jsonResponse);
From the log I can see that the database returns User objects in the correct order.
At the front-end, I have
success: function(jsonObj){
var json = JSON.parse(jsonObj);
var id = 0;
$.each(json,function(i,item) {
var time = item.time;
var name = item.name;
id++;
$("table#usertable tr:last").after('<tr><td>' + id + '</td><td width="20%">' + time +
'</td><td>' + name +
'</td></tr>');
});
},
But the order is changed.
I only noticed this when the returned list has large size (over 130 users).
I have tried to debug using Firebug, the "response tab" in Firebug shows the order of the list is different with the log in the servlet.
Did i do anything wrong?
EDIT: Example
{"0":{"time":"2011-07-18 18:14:28","email":"xxx#gmail.com","origin":"origin-xxx","source":"xxx","target":"xxx","url":"xxx"},
"1":{"time":"2011-07-18 18:29:16","email":"xxx#gmail.com","origin":"xxx","source":"xxx","target":"xxx","url":"xxx"},
"2":
,...,
"143":{"time":"2011-08-09 09:57:27","email":"xxx#gmail.com","origin":"xxx","source":"xxx","target":"xxx","url":"xxx"}
,...,
"134":{"time":"2011-08-05 06:02:57","email":"xxx#gmail.com","origin":"xxx","source":"xxx","target":"xxx","url":"xxx"}}
As JSON objects do not inherently have an order, you should use an array within your JSON object to ensure order. As an example (based on your code):
jsonObj =
{ items:
[ { name: "Stack", time: "..." },
{ name: "Overflow", time: "..." },
{ name: "Rocks", time: "..." },
... ] };
This structure will ensure that your objects are inserted in the proper sequence.
Based on the JSON you have above, you could place the objects into an array and then sort the array.
var myArray = [];
var resultArray;
for (var j in jsonObj) {
myArray.push(j);
}
myArray = $.sort(myArray, function(a, b) { return parseInt(a) > parseInt(b); });
for (var i = 0; i < myArray.length; i++) {
resultArray.push(jsonObj[myArray[i]]);
}
//resultArray is now the elements in your jsonObj, properly sorted;
But maybe that's more complicated than you are looking for..
As mentioned by ghayes , json objects are unordered.
There are multiple solutions to this problem.
You can use array and the sort it to get the ordered list.
You can use gson library to get the desired order of elements.
I would prefer the second option as it is easy to use.
As JSONObject is order less and internally uses Hashmap. One way to use it to download the all classes from org.json and use in your project directly by changing the internal HashMap implementation to LinkedHashMap in JSONObject.java file. below is the sorted json files
https://github.com/abinash1/Sorted-Json-Object

Categories