I have a JSON response that I get from the server like below
{
"questionList": [{
"qno": "1",
"state_name": "State1",
"category_name": "Category1",
"question_type": "type1",
"question": "This is question 11",
"options": ["No", "yes "]
},
{
"qno": "2",
"state_name": "State1",
"category_name": "Category1",
"question_type": "type1",
"question": "This is question12",
"options": ["No", "yes "]
},
{
"qno": "3",
"state_name": "State1",
"category_name": "Category2",
"question_type": "type2",
"question": "This is question 21",
"options": ["No ", "yes "]
},
{
"qno": "4",
"state_name": "State1",
"category_name": "Category3",
"question_type": "type1",
"question": "This is question 31",
"options": ["No ", "yes "]
},
{
"qno": "5",
"state_name": "State1",
"category_name": "Category3",
"question_type": "type1",
"question": "This is question 32",
"options": ["No ", "yes "]
}
]
}
Now I want to restructure it based on category so that questions with multiple same categories will fall under a single category and also few of my own variables. Below is a sample output of how it should look like.
[
{
"state": "State1",
"category": "Category1",
"questions": [
{
"questionID": "1",
"question": "This is question 11",
"options": ["No ", "yes "],
"status": 0,
"files": [],
"questionType": "type1"
},
{
"questionID": "2",
"question": "This is question12",
"options": ["No ", "yes "],
"status": 0,
"files": [],
"questionType": "type1"
}
]
},
{
"state": "State1",
"category": "Category2",
"questions": [
{
"questionID": "3",
"question": "This is question 21",
"options": ["No ", "yes "],
"status": 0,
"files": [],
"questionType": "type2"
}
]
},
{
"state": "State1",
"category": "Category3",
"questions": [
{
"questionID": "4",
"question": "This is question 31",
"options": ["No ", "yes "],
"status": 0,
"files": [],
"questionType": "type1"
},
{
"questionID": "5",
"question": "This is question 32",
"options": ["No ", "yes "],
"status": 0,
"files": [],
"questionType": "type1"
}
]
}
]
I'm not really an expert in JSON operations. Could anyone tell me shat should be the best way to solve this?
So if we take the questionList array from the json that you provided we can do the following.
Loop over each question in the questionList array.
Convert the question to the new format.
Check to see if we have come across the category before.
If we have not, we are going to create the category, add the new question to it, and add the category to our results array.
If we have found the category before then we are going to find it in the results array and add the new question to it.
Here is the code
let data = [{qno: "1", state_name: "State1", ... }, ... ] // notice that this is the questionList array and not an object
let categories = []; // to track the categories that you have found
let result = []; // where your results will be stored
data.forEach(question => {
// create the question
let newQuestion = {};
newQuestion.questionID = question.qno;
newQuestion.question = question.question;
newQuestion.options = question.options;
newQuestion.status = 0;
newQuestion.files = [];
newQuestion.questionType = question.question_type;
// check to see if we have the category, if not create it
if (categories.indexOf(question.category_name) === -1) {
// create a new category
let newCategory = {};
newCategory.state = question.state_name;
newCategory.category = question.category_name;
newCategory.questions = [];
newCategory.questions.push(newQuestion); // add the question to the category we just created
result.push(newCategory); // add the category to the result
categories.push(question.category_name); // track the category so we know not to create a new one
} else {
// search for the category
let foundCategory = result.filter(group => group.category === question.category_name);
// if we have found a category add the new question to it
if (foundCategory.length) {
foundCategory[0].questions.push(newQuestion);
}
}
});
console.log(result);
Related
I want to know how to filter data. I got data with category name but cannot filter category wise.Here is my data:
{
"TITLE": "tea",
"PRICE": "17",
"QTY": "1",
"CAT_ID": "33",
"CAT_NAME": "POPULAR PRODUCTS",
"TYPE": "veg"
},
{
"TITLE": "Coffee",
"PRICE": "102",
"QTY": "1 ",
"CAT_ID": "8",
"CAT_NAME": "MORNING SPECIAL",
"TYPE": "veg"
},
{
"TITLE": "Jeera chachh",
"PRICE": "42",
"QTY": "1",
"CAT_ID": "33",
"CAT_NAME": "POPULAR PRODUCTS",
"TYPE": "veg"
},
{
"TITLE": "Roti Ghee Wali",
"PRICE": "21",
"QTY": "1",
"CAT_ID": "33",
"CAT_NAME": "POPULAR PRODUCTS",
"TYPE": "veg"
},
{
"TITLE": "Paneer paratha",
"PRICE": "102",
"QTY": "1 ",
"CAT_ID": "8",
"CAT_NAME": "MORNING SPECIAL",
"TYPE": "veg"
},
{
"TITLE": "Mix paratha",
"PRICE": "102",
"QTY": "1",
"CAT_ID": "8",
"CAT_NAME": "MORNING SPECIAL",
"TYPE": "veg"
},
I already parse the data but not able to set in fragment according to category.Can anyone solve my issue.
Step 1: Store the data in database.
Step 2: Search
select * from table where CAT_NAME = 'your_filter_category'.
or better ....CAT_NAME like %your_filter_category%.
In Case of no database;
Store the Data in list.
HashMap<String, ArrayList<Item>> map = new HashMap<>();
ArrayList<Item> itemList = new ArrayList<>();
Loop on List{
Item item = fromLoop index;
if(map.contains(item.getCat())){
itemList = map.get(item.getCat());
itemList.put(item);
map.put(item.getCat(),itemList);
}else{
itemList.clear();
itemList.put(item);
map.put(item.getCat(),itemList);
}
}
//after loop you will get HashMap with keys as categories and Values as the list of selected key category.
Step 3: Publish the results.
Note: No one will do your homework here. the only thing we can do for you, we can assist you how to do.
enter your code to: JSON Formatter and you will see that something is invalid in your JSON, it has multiple root elements. Maybe you should store whole code in JSONArray like this: `
{
"features":
[{
"TITLE": "tea",
"PRICE": "17",
"QTY": "1",
"CAT_ID":"33",
"CAT_NAME": "POPULAR PRODUCTS",
"TYPE": "veg" },
{
"TITLE":"Coffee",
"PRICE": "102",
"QTY": "1 ",
"CAT_ID": "8",
"CAT_NAME":"MORNING SPECIAL",
"TYPE": "veg"
}]
}
I want to know that how can i fetch data through j sons. I.I am creating like this but did not get any data?
"arr": [1]
0: {
"obj": {
"id": "24"
"dispensary_id": "24"
"item_name": "item 3"
"total_feedback": "1"
"total_item": "13"
"followers": "7"
"follow_status": "following"
"category": "Edibles"
"strain": "Indica"
"tch": "0.70"
"cbd": "13.30"
"description": "testing items"
"image": "1447508911_greenfeed-3.jpg"
"qty1": "1/8 OZ"
"price1": "100"
"qty2": "1/4 OZ"
"price2": "200"
"qty3": "1/2 OZ"
"price3": "400"
"qty4": "1 OZ"
"price4": "799"
"dispensary_first_name": "Acme Dispensary"
"dispensary_last_name": "Smith"
"company": "Acme Dispensary"
"dispensary_image": "1449182412.png"
"city": "Irvine"
"state": "CA"
"status": "1"
}-
}-
-
"result": "true"
}
Use gson library for parsing JSON data. To learn how to use it go through with this link http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
your JOSN format is wrong it should be like this
{
"obj": {
"id": "24",
"dispensary_id": "24",
"item_name": "item 3",
"total_feedback": "1",
"total_item": "13",
"followers": "7",
"follow_status": "following",
"category": "Edibles",
"strain": "Indica",
"tch": "0.70",
"cbd": "13.30",
"description": "testing items",
"image": "1447508911_greenfeed-3.jpg",
"qty1": "1/8 OZ",
"price1": "100",
"qty2": "1/4 OZ",
"price2": "200",
"qty3": "1/2 OZ",
"price3": "400",
"qty4": "1 OZ",
"price4": "799",
"dispensary_first_name": "Acme Dispensary",
"dispensary_last_name": "Smith",
"company": "Acme Dispensary",
"dispensary_image": "1449182412.png",
"city": "Irvine",
"state": "CA",
"status": "1"
}
}
for this you can check on whether your json is valid or not http://jsonlint.com/
for creating json you can use some library like
JSONObject jsonObject = new JSONObject();
jsonObject.add("key", "value");
jsonObject.add("key", "value");
Anybody knows how to parse the "title" content in this JSON fromat ?
JSON:
{
"news": [
{
"Id": "58710",
"c_id": "6",
"title": "റയില്വേയില് നിക്ഷേപം നടത്താന് എല്ഐസി",
"image": "http://4malayalees.com/malayalamNews/thumb/58710.jpg",
"news": " വ്യത്യസ്ത പദ്ധതികള്ക്കായി അടുത്ത അഞ്ച് വര്ഷത്തിനുള്ളില് എല്ഐസി റെയില്വേയ&"
},
{
"Id": "58551",
"c_id": "6",
"title": "മലയാളിയുടെ ന്യൂസ് പോര്ട്ടല് ഇനി റൂപര്ട്ട് മര്ഡോക്കിന് സ്വന്തം",
"image": "http://4malayalees.com/malayalamNews/thumb/58551.jpg",
"news": "സഹദ് എന്ന പേര് ഒരുപക്ഷെ മലയാളികള്ക്ക് സുപരിചിതമല്ലായിരിക്കാം, എന്നാല് മാധ്യമ ő"
}
]
}
Thanks in advance
I am developing a quiz application and my questions are in a Json file
{
"name": "JHS ASANTE TWI",
"course_id": "73",
"courseID": "01JS88",
"package_code": "JHS",
"description": "",
"category": "",
"author": "content#exams.com",
"questions": {
"58242": {
"qid": "58242",
"topic": "1268",
"instructions": "Yi nea εne nea yεasensane aseε no asekyerε bɔ abira",
"text": "<p>Kofi de sika no maa <span style=\"text-decoration: underline;\">aberante<span>ε</span></span> bi.</p>",
"resource": "",
"qtype": "SINGLE",
"confirmed": "1",
"public": "1",
"flagged": "0",
"updated_at": "2014-07-10 12:29:33",
"rating": 0,
"answers": [
{
"id": "250310",
"text": "<p>ababaawa</p>",
"value": "1",
"solution": ""
},
{
"id": "250311",
"text": "<p>ab<span>ɔfra</span><span><br /></span></p>",
"value": "0",
"solution": ""
},
{
"id": "250312",
"text": "<p>aberewa</p>",
"value": "0",
"solution": ""
},
{
"id": "250313",
"text": "<p>abarimaa</p>",
"value": "0",
"solution": ""
}
]
},
"58245": {
"qid": "58245",
"topic": "1268",
"instructions": "Yi nea εne nea yεasensane aseε no asekyerε bɔ abira",
"text": "<p>Mehunuu m'adamfo bi nnora <span style=\"text-decoration: underline;\">an</span><span style=\"text-decoration: underline;\">ɔpa</span>.</p>\n<p> </p>\n<p> </p>",
"resource": "",
"qtype": "SINGLE",
"confirmed": "1",
"public": "1",
"flagged": "0",
"updated_at": "2014-07-10 12:43:29",
"rating": 0,
"answers": [
{
"id": "250329",
"text": "<p>awia</p>",
"value": "1",
"solution": ""
},
{
"id": "250328",
"text": "<p>anwummer<strong></strong>ε</p>",
"value": "0",
"solution": ""
},
{
"id": "250327",
"text": "<p>ahemadakye</p>",
"value": "0",
"solution": ""
},
{
"id": "250326",
"text": "<p>owigyinaeε</p>",
"value": "0",
"solution": ""
}
]
},
"58246": {
"qid": "58246",
"topic": "1268",
"instructions": "Yi nea εne nea yεasensane aseε no asekyerε bɔ abira",
"text": "<p>Asomaning <span style=\"text-decoration: underline;\">kuro</span> no so.</p>",
"resource": "",
"qtype": "SINGLE",
"confirmed": "1",
"public": "1",
"flagged": "0",
"updated_at": "2014-07-10 12:53:00",
"rating": 0,
"answers": [
{
"id": "250330",
"text": "<p><span>ɔmansini</span></p>",
"value": "0",
"solution": ""
},
{
"id": "250331",
"text": "<p><span>ɔman</span></p>",
"value": "0",
"solution": ""
},
{
"id": "250332",
"text": "<p>wiase</p>",
"value": "0",
"solution": ""
},
{
"id": "250333",
"text": "<p>akuraa</p>",
"value": "1",
"solution": ""
}
]
}
}
}
My question is: how do I access the next question of "questions" when i click next for the next question since "58242", "58245", etc are all dynamic values?
the answer on this post was very helpfull but now i want to now how loop through the questions How to parse a dynamic JSON key in a Nested JSON result
it helped me get the currentdynamic value but does not give me the next question when i click on next
private View.OnClickListener nextListener = new View.OnClickListener() {
public void onClick(View v) {
setAnswer();
try {
if (quesIndex != searchResult.getJSONObject("questions").length() - 1) {
quesIndex++;
progress.setProgress(0);
progress.setMax(100);
} else {
Intent myIntent = new Intent(TestActivity.this, Assesment.class);
myIntent.putExtra("intVariableName", score);
startActivity(myIntent);
}
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (quesIndex == searchResult.getJSONObject("questions").length() - 1) {
next.setText("Finish");
Intent myIntent = new Intent(TestActivity.this, Assesment.class);
myIntent.putExtra("intVariableName", score);
startActivity(myIntent);
// close this activity
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
showQuestion(quesIndex, review);
}
};
will appreciate the help thanks :)
Not sure what you problem is. Seems like the solution is in the link you gave above.
JSONObject questions = result.getJSONObject("questions");
Iterator keys = questions.keys();
//go through every question
while (keys.hasNext()) {
String currentDynamicKey = (String)keys.next();
JSONObject currentQuestion = questions.getJSONObject(currentDynamicKey);
}
I'm having an array of objects represented as JSON string that will be coming from an API server. Let's suppose we have some Movie Categories and actual Movies that belong to each category:
[
{
"id": "1",
"name": "Action",
"movies": [
{
"id": "1",
"name": "Movie 1",
"description": "Movie 1 Description",
"other": "Other..."
},
{
"id": "2",
"name": "Movie 2",
"description": "Movie 2 Description",
"other": "Other..."
}
]
},
{
"id": "2",
"name": "Drama",
"movies": [
{
"id": "3",
"name": "Movie 3",
"description": "Movie 3 Description",
"other": "Other..."
},
{
"id": "4",
"name": "Movie 4",
"description": "Movie 4 Description",
"other": "Other..."
}
]
}
]
The users of my android app will need to be able to browse through categories/movies.
Which of the following scenarios is better regarding the performance of the code and optimal memory usage?
Assume that there will be many channels and categories.
1. Parse the JSON string once, create ArrayLists of Category and Movie objects for each category that I will later use them for populating lists.
2. Create a Parser with few methods like get_total_channels, get_channel, get_category that will always parse the contents of the JSON string to return me the appropriate data to populate the lists.
3. Any other suggestion?