JSON parsing multiple nested arrays - arrays

I am trying to parse below json, which has multiple nested lists (input & output), how do I parse it ?
{
"status":"current",
"entry":[{
"item":{
"name":"Task1",
"identifier":"T00001",
"input":[{
"type":{
"text":"InputTask1-1"
},
"valueString":"Weekly"
},
{
"type":{
"text":"InputTask1-2"
},
"valueString":"Daily"
}
],
"output":[{
"type":{
"text":"OutputTask1-1"
},
"valueString":"Daily"
},
{
"type":{
"text":"OutputTask1-2"
},
"valueString":"Weekly"
}
]
}
},
{
"item":{
"name":"Task2",
"identifier":"T00002",
"input":[{
"type":{
"text":"InputTask2-1"
},
"valueString":"Weekly"
},
{
"type":{
"text":"InputTask2-2"
},
"valueString":"Daily"
}
],
"output":[{
"type":{
"text":"OutputTask2-1"
},
"valueString":"Daily"
},
{
"type":{
"text":"OutputTask2-2"
},
"valueString":"Weekly"
}
]
}
}
]
}
Looking for delimited output file like this:
"TaskName"|"TaskId"|"InputName"|"InputValue"|"OutputName"|"OutputValue"
Task1|T00001|InputTask1-1|Weekly|outputDummyText|outputDummyValue
Task1|T00001|InputTask1-2|Daily|outputDummyText|outputDummyValue
Task1|T00001|inputDummyText|inputDummyValue|OutputTask1-1|Daily
Task1|T00001|inputDummyText|inputDummyValue|OutputTask1-2|Weekly
Task2|T00002|InputTask2-1|Weekly|outputDummyText|outputDummyValue
Task2|T00002|InputTask2-2|Daily|outputDummyText|outputDummyValue
Task2|T00002|inputDummyText|inputDummyValue|OutputTask2-1|Daily
Task2|T00002|inputDummyText|inputDummyValue|OutputTask2-2|Weekly

Use Kotlin and Gson library.
Define your model:
data class MyData(val status: String, val entry: List<Entry.ItemContainer>) {
data class Entry(val itemContainer: List<ItemContainer>) {
data class ItemContainer(val item: Item) {
data class Item(
val name: String,
val identifier: String,
val input: List<TypeContainer>,
val output: List<TypeContainer>
) {
data class TypeContainer(val valueString: String, val type: Type) {
data class Type(val text: String)
}
}
}
}
}
Read json string from file:
val json = File("data.json").readText()
Map the data to the defined model using Gson:
val myData = Gson().fromJson<MyData>(json, MyData::class.java)
Print the result in desired format (or save it to file):
println("\"TaskName\"|\"TaskId\"|\"InputName\"|\"InputValue\"|\"OutputName\"|\"OutputValue\"")
for (itemContainer: MyData.Entry.ItemContainer in myData.entry) {
with(itemContainer.item) {
for (typeContainer in input) {
println("$name|$identifier|${typeContainer.type.text}|${typeContainer.valueString}|outputDummyText|outputDummyValue")
}
for (typeContainer in output) {
println("$name|$identifier|inputDummyText|inputDummyValue|${typeContainer.type.text}|${typeContainer.valueString}")
}
}
}

Try this
JSONObject jsonParent = new JSONObject(response);
JSONArray jsonarray = jsonParent .getJSONArray("entry");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject c = jsonarray.getJSONObject(i);
JSONObject jsonItem = c.getString("item");
JSONArray inputItemArray = jsonItem.getJSONArray("input");
for (int j = 0; j < inputItemArray.length(); j++) {
JSONObject inputItemObj = inputItemArray .getJSONObject(j);
String invalueString = inputItemObj.getSting("valueString ");
}
JSONArray outputItemArray = jsonItem.getJSONArray("output");
for (int k = 0; k < outputItemArray.length(); k++) {
JSONObject outputItemObj = outputItemArray.getJSONObject(K);
String outvalueString = outputItemObj.getSting("valueString ");
}
}

Related

How to fetch two or more json file data in one page

for example, in my project, I have 4 steps, in 2 steps already pass (class id and subject id)the JSON, now I want to know how to add two JSON on a one-page example topic list
[
{
"_IdTopicMaster": "1",
"TopicName": "demo1",
"IdSubjectMaster": "1"
},
]
Contentlist JSON here
{
"IdContentMaster": "11",
"IdTopicMaster": "1",
"IdContentTypes": "2",
"DisplayName": "contentdemoname",
"ContentPath": "demo/Kannada/G1/Maths/VML",
"ContentName": "KG1MVML1.1 ",
"thumbnail": "assets/application/icons/Englishmedium/Class 1/Maths/dummy.png",
"format": ".mp4"
},
here is my JSON function code
Future<void> getListOfMonths() async {
final String fileText = await
rootBundle.loadString('assets/database_json/contentlist.json');
Map<String, dynamic> user = jsonDecode(fileText);
List<dynamic> list = user['data'];
for (int i = 0; i < list.length; i++) {
if (selectedtl == int.parse(list[i]['Class_id'])) {
if (selectedsubtopic == int.parse(list[i]['IdSubjectMaster'])) {
if (selectedModules == int.parse(list[i]['_IdTopicMaster'])) {
listOfWeekWidgets.add(GestureDetector(
onTap: () {
filePath = list[i]['ContentPath'];
fileName = list[i]['ContentName'];
cpformat = list[i]['format'];
subTopName = list[i]['SubjectName'];
checkIfPathIsPicked(int.parse(list[i]["_IdTopicMaster"]));
},
child: ListView.builder(
itemCount: 5,
itemBuilder: (context, index) {
return Container();
}),
));
setState(() {
listOfWeekWidgets;
});
}
}
}
}
}

Populate an array of array of objects

I must populate an array of array of objects to get something like this:
let dataObj = [
[
{ content: "test1"},
{ content: "test2"},
{ content: "test3"}
],
[
{ content: "test4"},
{ content: "test5"},
{ content: "test6"}
]
]
I start from an array of arrays like this:
data = [["test1", "test2", "test3"], ["test4", "test5", "test6"]]
I tried with:
let dataObj = <any>[[{ }]];
for (let i = 0; i < data.length; i++) {
for (let j=0; j < data[i].length; j++) {
dataObj[i][j].content = data[i][j];
}
}
but after populating the first ([0][0]) it stops and the error is an
uncaught in promise...
(I work in Angular-TypeScript)
I tried also with:
dataObj.push(i,j,{content: data[i][j]});
It gets a result but it's completely wrong.
Add an array into the root array.
Add an object into the nested array.
let dataObj: { content: any;[key: string]: any }[][] = [];
for (let i = 0; i < data.length; i++) {
dataObj.push([]);
for (let j = 0; j < data[i].length; j++) {
dataObj[i].push({ content: data[i][j] })
}
}
Alternatively, you can work with .map().
let dataObj: { content: any;[key: string]: any }[][] = [];
dataObj = data.map(x =>
x.map(y => {
return { content: y };
})
);
Sample TypeScript Playground

Adding paragraph text input by loop [TypeScript]

I have this variable in my TypeScript :
data = {
"paragraphs": [
{ "paragraph": "" }
]
}
When the screen is loaded, I want to add the { "paragraph": "" } in the array to become like as follow.
data = {
"paragraphs": [
{ "paragraph": "" },
{ "paragraph": "" },
{ "paragraph": "" }
]
}
So what I did was, I make a for loop to keep adding the { "paragraph": "" } in the array but it's not completed yet.
let dataParag = 3; // The int value will keep changing based on data from database
for (var i = this.data.paragraphs.length; i <= dataParag; i++) {
this.data.paragraphs = [
{ "paragraph": "" } // The paragraph will be keep added in here but I don't have any idea on how to add it
];
}
Is there any good way to add it dynamically?
Oh nevermind as I found the solution for this. This is how I do the thing :
let dataParag = 3;
for (var i = 1; i < dataParag; i++) {
this.data.paragraphs.push({ "paragraph": "" });
}

Angular2 JSON Duplication Deletion

I am working with a large JSON file holding information about instructors at my school. I want to be able to pull all the teachers names from this list so I can then put them into Firebase. However, whenever I loop over my JSON file and try to filter out all the duplicate teacher names I still end up with duplicates even when I try to do a second round of deletion. The JSON looks like this:
{
"Id": "1",
…
"Instructor": "name1, name2, name3",
…
},
{
"Id": "2",
…
"Instructor": "name1",
…
},
{
"Id": "3",
…
"Instructor": "name1, name2",
…
}
As seen above sometimes there is just one name, other times there are multiple. I handle this though in my logic but no matter what I still end up with duplicates. If anyone can help me come up with a way to solve this it would be greatly appreciated. I'll add my code that I have already below.
public remove_duplicates(arr: any[]): any[] {
let output: any[] = [];
for (let i = 0; i < arr.length; i++) {
let instruc: any[] = arr[i].Instructor.split(',');
for (let j = 0; j < instruc.length; j++) {
let push: boolean = true;
arr[i].Instructor = instruc[j];
for (let k = 0; k < output.length; k++) {
let i1: string = output[k].Instructor;
let i2: string = arr[i].Instructor;
if (i1.trim().localeCompare(i2.trim()) == 0) {
push = false;
}
}
if (push)
output.push(arr[i]);
}
}
console.log(output.length);
for (let k = 0; k < output.length; k++) {
for (let i = k + 1; i < output.length; i++) {
if (new String(output[i].Instructor).valueOf().trim()
=== new String(output[k].Instructor).valueOf().trim()) {
output.splice(i, 1);
}
}
}
for (let k = 0; k < output.length; k++) {
console.log(output[k].Instructor);
}
console.log(output.length);
return arr;
}
ngOnInit() {
this.http.get('courses.json').take(1)
.map((res: Response) => res.json())
.subscribe(
data => {
this.list = data;
},
err => console.log(err),
() => this.remove_duplicates(this.list)
);
}
There isn't anything specific to Angular 2 that you're trying to do here. This is just vanilla JS.
Try something like this:
public remove_duplicates(arr) {
let seen = {};
let uniqueInstructorNames = [];
arr.forEach(function(item) {
let instructorNames = item.Instructor.split(',');
Array.prototype.push.apply(uniqueInstructorNames, instructorNames.filter( name => {
return seen.hasOwnProperty(item) ? false : (seen[item] = true);
}));
});
return uniqueInstructorNames;
}

how to fill <array> struct by another struct

My app in Xcode with swift language programming :
I have a struct like:
struct PageFilter {
var key: Int?
var title: NSString?
}
And then I have the values in:
filters are coming from API and i am saving them to extractedFilter
if let filters = filters {
for filter in filters {
var extractedFilter = PageFilter()
extractedFilter.key = filter["key"].integerValue
extractedFilter.title = filter["title"].stringValue
}
}
I have an array of page filter like :
lazy var availableFilters = Array<PageFilter>()
I want to fill the availableFilters with ExtractedFilter.
******* *i fixed the issue by a loop like this code :
var strFilter : String = ""
for var i = 0; i < self.newFilterList.availableGuildFilters.count; i++ {
let guildFilter = self.newFilterList.availableGuildFilters[i]
if guildFilter.selected {
strFilter += "\(guildFilter.key),"
}
}
thanks to all*
The following Swift 1.2 playground code would do it - I have put in a function to simulate the call to the API
//: Playground - noun: a place where people can play
import Cocoa
struct PageFilter {
var key: Int?
var title: NSString?
}
// this would be replaced by whatever way you get your filters from the API
func getFiltersFromApi() -> [PageFilter]? {
// return nil // uncomment this line to demo the API returning nothing
return [PageFilter(key: 1, title: "one"),
PageFilter(key: 2, title: "two"),
PageFilter(key: 3, title: "three"),
PageFilter(key: nil, title: nil)
]
}
let filters: [PageFilter]? = getFiltersFromApi() // API call, this could return nil
let extractedFilters: [PageFilter]
if let filters = filters {
extractedFilters = filters.map { filter in
PageFilter(key: filter.key, title: filter.title)
}
} else {
extractedFilters = []
}
for filter in extractedFilters {
println("key: \(filter.key), title: \(filter.title)")
}
Alternatively you could have your lazy var like this
var availableFilters: [PageFilter] = {
let filters: [PageFilter]? = getFiltersFromApi() // API call, this could return nil
if let filters = filters {
return filters.map { filter in
PageFilter(key: filter.key, title: filter.title)
}
} else {
return []
}
}()
The code is similar to Leonardo's answer, the main difference being the use of the map function instead of for ... in ...
Try like this:
struct PageFilter {
var key = Int()
var title = String()
}
var filters:[PageFilter]? = []
filters = [PageFilter(key: 1, title: "one"), PageFilter(key: 2, title: "two"), PageFilter(key: 3, title: "three")]
var extractedFilter = Array<PageFilter>()
if let filters = filters {
for filter in filters {
extractedFilter.append(PageFilter(key: filter.key, title: filter.title))
}
}
println(extractedFilter[1].key) // "2"
println(extractedFilter[1].title) // "two"
I fixed the issue by a loop like this:
var strFilter : String = ""
for var i = 0; i < self.newFilterList.availableGuildFilters.count; i++ {
let guildFilter = self.newFilterList.availableGuildFilters[i]
if guildFilter.selected {
strFilter += "\(guildFilter.key),"
}
}

Resources