How can I iterate a json object and get it's values in dart.
Below is an Example json object that is want to get it's value.
"SomeJsonList": {
"image": ["imageUrl1", "imageUrl2"],
"video": ["videoUrl1", "videoUrl2"]
}
To get the values of the image and video object as a list.
The output i am looking for:
var urlList = [];
urlList = [imageUrl1, imageUrl2,videoUrl1,
videoUrl2]
You can merge list items using addAll as below
void main() {
Map<String, List<String>> json = {
"image": ["imageUrl1", "imageUrl2"],
"video": ["videoUrl1", "videoUrl2"]
};
List<String>? img = json["image"];
List<String>? vid = json["video"];
List<String> list = [];
list.addAll(img!); // better check if `img` not null instead of "!"
list.addAll(vid!); // better check if `vid` not null instead of "!"
// list.addAll(xyz); // some more if needed
print(list); // [imageUrl1, imageUrl2, videoUrl1, videoUrl2]
}
My code snippet for nested json object:
JsonArray arr = jsonObject.getAsJsonArray("data");
for(int i = 0; i < arr.size(); i++) {
String _Id = arr.get(i).getAsJsonObject().get("_id").getAsString();
String Name = arr.get(i).getAsJsonObject().get("name").getAsString();
int Trips = arr.get(i).getAsJsonObject().get("trips").getAsInt();
}
You can parse JSON using JSON.parse();
let exampleJSON = '{ "id": 245, "name": "Mike" }';
const obj = JSON.parse(exampleJSON);
console.log(obj.id); // 245
I'm trying to create an array of arrays that are grouped according to their lengths (strings), such that the array below:
var testA = ["carts","carts","cars","cars","ca","ca", "ca","a","a","a","a"];
would become:
var sortedArrays = [["carts","carts"], ["cars","cars"],["ca","ca","ca"], ["a","a","a","a"]]
I am currently trying the loop below but simply cannot get this to work. I know it'll be something simple, but I've spent so long trying to complete this with no that it's proving incredibly frustrating.
var testA = ["carts","carts","cars","cars","ca","ca", "ca","a","a","a","a"];
var sortedArrays = [];
for(i=0; i < testA.length; i++){
longestWord = 0;
wordHolder = []
wordHolder.push(testA[i])
if (testA[i].length > longestWord){
longestWord = testA[i].length
wordHolder.push(testA[i])
}
sortedArrays.push(wordHolder)
}
Any help will be greatly appreciated
What about the following code (Swift, but it should be easy to reformulate it in other languages):
let testA = ["carts","carts","cars","cars","ca","ca", "ca","a","a","a","a"]
var maxLength = 0
for string in testA {
if string.count > maxLength { maxLength = string.count }
}
var sortedArrays: [[String]] = []
for nextLength in 0 ... maxLength {
let invertedLength = maxLength - nextLength
let nextArray = testA.filter { $0.count == invertedLength }
sortedArrays.append(nextArray)
}
This code creates also empty arrays, which can of course easily be skipped.
The question, of course, is what your requirements are. The code above is compact, but it is not fast for large arrays...
For large arrays, it would be better, first to sort testA, and then to extract the elements.
Sticking with java script, I was able to do the following. My assumption is the words are already sorted descending by length and that there is only one word of each length. That's based on what you were doing. I think what was going on is that too much was getting initialized or reset each time through the loop.
var testA = ["carts", "carts", "cars", "cars", "ca", "ca", "ca", "a", "a", "a", "a"];
var sortedArrays = [];
var wordHolder = []; // took outside loop to ensure initialized
var curLength = testA[0].length;// assuming here that testA not empty
for (var i = 0; i < testA.length; i++) {
if (testA[i].length === curLength) { // more of the same
wordHolder.push(testA[i]);
} else { // new block starts
curLength = testA[i].length;
sortedArrays.push(wordHolder);
// alert (wordHolder)
// alert (sortedArrays)
wordHolder = [];
wordHolder.push(testA[i]);
}
}
sortedArrays.push(wordHolder);// add the last one
var files = NSMutableArray()
...
for (var i = 0; i < files.count; i++) {
var f = files[i] as [String: AnyObject]
f["selected"] = true
}
When I debug the code, the "selected" property of f is set correctly. but the corresponding element in the files remains unchanged. Why? Thanks.
I am not sure what is going on with using an NSMutableArray here... but perhaps it's working like a value type instead of a reference type. Try replacing the item in the array with the modified version.
files.replaceObjectAtIndex(i, withObject: f)
Place it after you make your modification.
var files = NSMutableArray()
//...
for (var i = 0; i < files.count; i++) {
var f = files[i] as! [String: AnyObject]
f["selected"] = true
files.replaceObjectAtIndex(i, withObject: f)
}
If you were using a swift array type, something like this should work instead.
var files = [[String: AnyObject]]()
//...
for (var i = 0; i < files.count; i++) {
var f = files[i] as [String: AnyObject]
f["selected"] = true
files[i] = f;
}
The reason corresponding elements of file is not changing is that you are not modifying it at all you are just altering values of var f inside the loop.
Try this code:
var files = [Dictionary<String,AnyObject>]()
// Probably you are trying to make array of dictionary objects
for var i = 0; i < 10 ; i++ {
files[i]["selected"] = true
}
I have this JSON
"DocumentType": {
"propertyName": "DocumentType",
"propertyType": "Text",
"propertyValue": "Fire"
},
"adsfsadf": {
"propertyName": "adsfsadf",
"propertyType": "Text",
"propertyValue": "sfsfdffsd"
}
I want to search and retrieve the node that has propertyName="DocumentType"? I have tried
result.get("//#propertyName='DocumentType'/..")
And also tried
result.get("//propertyName[text()='DocumentType'/..")
And get a null object each time.
Try the following code
JSONParser p = new JSONParser();
Map<String, Object> myMap = p.parseJSON(new InputStreamReader(YOUR JSON INPUT STREAM));
ArrayList<Map<String, String>> myList = (ArrayList<Map<String,String>>)myMap.get("DocumentType");
for (int i = 0; i < myList.size(); i++) {
Map<String, String> dtls = myList.get(i);
String prop = dtls.get("propertyName"));
}
Thanks!