How to iterate JSON objects - arrays

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]
}

Related

Create an empty array and send it to Firestore with an empty value in Flutter?

I want to create an empty array in Firestore while posing a feed. But the array is showing null in Firestore. Here is my code. Please help.
class FeedModel {
final String imgUrl;
final String desc;
final String authorName;
final String profileImg;
final String title;
final int likeCount;
List<String> strArr = []; // this the array i want to create it in firestore
FeedModel({this.imgUrl, this.desc,this.authorName,this.profileImg,this.title,this.likeCount, this.strArr});
Map<String, dynamic> toMap(){
return {
"imgUrl" : this.imgUrl,
"desc" : this.desc,
"authorName" : this.authorName,
"profileImg" : this.profileImg,
"like_count" : this.likeCount,
"liked_user_id" : this.strArr
};
}
}
Here is the send data code:
Future<void> _sendData() async {
try {
final StorageReference firebaseStorageRef = FirebaseStorage.instance.ref().child('myimage.jpg');
final StorageUploadTask task = firebaseStorageRef.putFile(_image);
StorageTaskSnapshot taskSnapshot = await task.onComplete;
String downloadUrl = await taskSnapshot.ref.getDownloadURL();
final String pname = myController.text;
final String pimgurl = downloadUrl;
final String pauthorName = "Sachin Tendulkar";
final String pprofileImg = "https://i.picsum.photos/id/564/200/200.jpg?hmac=uExb18W9rplmCwAJ9SS5NVsLaurpaCTCBuHZdhsW25I";
final String ptitle = "Demo Data";
final int plikeCount= 0;
List<String> pLikeduserId; // This line returning null as show in image
print(pimgurl);
final FeedModel feeds = FeedModel(imgUrl: pimgurl ,desc: pname,authorName: pauthorName ,profileImg: pprofileImg,title: ptitle,likeCount: plikeCount, strArr : pLikeduserId );
insertData(feeds.toMap());
} catch (e) {
print(e);
}
}
null image:
want to get like below image:
How can i send array like last image when creating a feed?
If you want an array in a field, even an empty array, you will have to assign it an actual list value. Right now, by not assigning any actual list value at all, you're effectively assigning a null value to the liked_user_id.
So, just give it a value:
List<String> pLikeduserId = [];
That will write an empty list field.
There isn't much of a reason to store it as an array with a value of ''. Instead, it would be better to null check when receiving the value from firebase by using something like: liked_userid = /*insert method of getting firebase user ID*/??[]
This way when you use the liked_userid it won't be null and will be an empty list.
If you really want a list with the value of '' inside than change the insides of the toMap function:
Map<String, dynamic> toMap(){
return {
"imgUrl" : this.imgUrl,
"desc" : this.desc,
"authorName" : this.authorName,
"profileImg" : this.profileImg,
"like_count" : this.likeCount,
"liked_user_id" : this.strArr=[]?['']:this.strArr//line that was changed
};
}
This would make it so that you will have an array with [''] inside but I would still recommend the first method I showed.
Do this to create an array with an empty string.
Map<String, dynamic> toMap() {
return {
'liked_user_id': List.generate(1, (r) => "")
};
}
await _fireStore.collection("COLLECTION_NAME").document("DOUCUMENT_NAME").setData({
"KEY_VALUE": [],
});
This creates an empty Array in Cloud FireStore.

Add Parse array to dictionary swift

I have some objects in parse and I am getting the data successfully as [PFObjects]. The issue is that I am trying to add the array elements [PFObjects] to a dictionary as values. But I keep getting an empty dictionary, so the values are not added to the dictionary. The dictionary count is also 0.
This is what I tried so far:
var postDictionary = [String:[AnyObject]]()
query.findObjectsInBackground(block: { (posts: [PFObject]?, error:Error?) in
if let unwrappedPosts = posts {
for posts in unwrappedPosts {
if let postText = posts.object(forKey: "title") as?String {
self.titleArray.append(postText)
print("count", self.titleArray.count) // count 10
self.postDictionary["title"]?.append(self.titleArray as AnyObject)
**try to force unwrap **
self.postDictionary["title"]!.append(self.titleArray as AnyObject), and the app crashed
for (title, text) in self.postDictionary {
print("\(title) = \(text)")
}
print("Dictionay text count",self.postDictionary.count) // count is 0
}
}
}
})
This syntax is very confusing
self.titleArray.append(postText)
self.postDictionary["title"]?.append(self.titleArray as AnyObject)
You append a string to an array and then you are going to append the array to the array in the dictionary. I guess this is not intended.
I recommend to map the title strings and set the array for key title once
var postDictionary = [String:[String]]()
query.findObjectsInBackground(block: { (posts: [PFObject]?, error:Error?) in
if let unwrappedPosts = posts {
self.titleArray = unwrappedPosts.compactMap { $0.object(forKey: "title") as? String }
self.postDictionary["title"] = self.titleArray
for (title, text) in self.postDictionary {
print("\(title) = \(text)")
}
print("Dictionay text count",self.postDictionary.count) // count is 0
}
})
Never use AnyObject if the type is more specific.
The proper way of adding to a dictionary is using updateValue because as far as i can see that you don't have the key "title" in your dictionary and you are appending values to unknown key i guess.
This should help:
titleArray.append(postText)
postDictionary.updateValue(titleArray as [AnyObject], forKey: "title")
for (key,value) in postDictionary {
print("\(key) \(value)")
}
Finally this should print:
title [posts1, posts2, posts3]

Copy Array from http request to other array in Angular

I pretty new to angular and I have a question.
I need 2 arrays for ng2-charts, one with labels and one with data.
I make http request to AWS and I got this json
{
"System1": [
{
"name": "MF3",
"descr": "Multifilo MF3",
"speed": [1,2,3,4],
"time": ["10.01", "10.02", "10.03", "10.04"]
}
]
}
I assing all the result to result: Array<SystemModel>;
For use speed and time on ng2-charts I have to copy the two array speed and time on new array: public lineChartSpeed: Array<number> = []; and public lineChartTime: Array<any> = [];
How can I copy this 2 array on my new array? I know how to access to data only on html template, but not on typscript file...
My component is:
public lineChartSpeed: Array<number> = [];
lineChartTime: Array<any> = [];
result: Array<ImpiantoModel>;
getdata() {
this.http.get<SystemModel[]>(this.myUrl)
.subscribe(
data => { this.result = data;
// perform the copy of speed and time on lineChartTime and lineChartSpeed
});
}
How can I copy the array?
If you need more details, please ask in the comments!
thank you !
var system1 = {
"System1": [
{
"name": "MF3",
"descr": "Multifilo MF3",
"speed": [1,2,3,4],
"time": ["10.01", "10.02", "10.03", "10.04"]
}
]
}
var speed = system1.System1[0].speed
var time = system1.System1[0].time
console.log('Array of Speed', speed)
console.log('Array of Time', time)
//Merge or concatenate two Arrays
var newArray = [...speed, ...time]
console.log('Merged or concatenated Arrays', newArray)
Use slice operator to create a new copy of the array
this.result = data.slice();
this.lineChartSpeed = [].concat(this.result[0].speed);
this.lineChartTime = [].concat(this.result[0].time);

How dynamically transform my "Object" to List in ng-model at view

I'm trying to transform my object to list dynamically, so I'm building at view instead of declaring at controller.
I don't want to declare like this: custom_fields.title_field.type_text_field = [] because the title_field is built dynamic, it could be any kind of text like full_name
My json as is:
"custom_fields":{
"title_dynamic_generate_field":{
"type_text_field":{
"name":"John",
"first_name":"Wick"
},
"type_boolean_field":{
"is_badass": true,
"is_good_movie": true
},
"type_select_field": {
"this_select": 1,
"i_got_this": "nope i didnt got this"
}
},
And to be:
"custom_fields":{
"title_dynamic_generate_field":{
"type_text_field":[{
"name":"John",
"first_name":"Wick"
}],
"type_boolean_field":[{
"is_badass": true,
"is_good_movie": true
}],
"type_select_field": [{
"this_select": 1,
"i_got_this": "nope i didnt got this"
}]
},
the object I'm trying to transform into array is type_text_field which can be dynamic too, like type_date_field or type_select_field and so on.
My ng-model is like this:
ng-model="objectApp.application.applicant.custom_fields[layout.dynamic_title][input.type][input.variable]"
the [input.type] is that I'm trying to transform into array, how can I achieve this? I tried to use $index, but got strange results.
We can do it by 2 solutions:
There is a question about your task:
? how you want handle if we have more than one type_text_field in title_dynamic_generate_field? because you want to convert it to "type_text_field":[{},...]
however my answers about the question are:
If we know what's the dynamic params which we want to send theme as json, i mean if we know what is the key of title_dynamic_generate_field or type_text_field, we do as this sample:
var data = {
"custom_fields": {
dynamicParamIs1: 'title_dynamic_generate_field',
dynamicParamIs2: 'type_text_field',
"title_dynamic_generate_field": {
"type_text_field": {
"name": "John",
"first_name": "Wick"
}
}
}
}
var paramHelper1 = json.custom_fields[json.custom_fields.dynamicParamIs1];
var paramHelper2 = json.custom_fields.dynamicParamIs2;
var solutionA = function (object, as) {
var array = [];
for (var key in object) {
var newObject = object[key];
array.push(newObject);
}
object[as] = array;
}
solutionA(paramHelper1, paramHelper2);
We changed a model of our json which can help us to detect (find) the keys
If we don't know what is the dynamic params are, we do as this:
var data = {
"custom_fields": {
"title_dynamic_generate_field": {
"type_text_field": {
"name": "John",
"first_name": "Wick"
}
}
}
}
var solutionB = function (json) {
var array = [];
for (var key in json) {
var j1 = json[key];
for (var key2 in j1) {
var j2 = j1[key2];
for (var key3 in j2) {
var fullObject = j2[key3];
array.push(fullObject);
j2[key3] = array;
}
}
}
}
solutionB(data);
This sample is manual which we use nested for to detect the keys name

Processing error message 'The function getJSONArray(JSONArray) does not exist'

i am not sure why i am getting the error message 'The function getJSONArray(JSONArray) does not exist' when i run this sketch that uses a json query to Weather Underground. That comment seems illogical since Processing is recognising the id ref for the JSONArray.
The .json can be read here: http://api.wunderground.com/api/97a2805510de59e9/hourly/q/pws:IENGLAND274.json
Any thoughts? Thanks.
import com.francisli.processing.http.*;
HttpClient client;
String data;
com.francisli.processing.http.JSONObject weatherInfo;
JSONArray hourly_forecast;
int last = 0;
PImage img;
Float humidity = 50.2;
void setup() {
size(700, 700);
client = new HttpClient(this, "api.wunderground.com");
client.GET("/api/97a2805510de59e9/hourly/q/pws:IENGLAND274.json");
background(255);
}
void responseReceived(HttpRequest request, HttpResponse response) {
println(response.getContentAsString());
weatherInfo = response.getContentAsJSONObject();
JSONArray hourly_forecast = weatherInfo.getJSONArray(hourly_forecast);
}
There is no method called getJSONArray() that takes in a JSONArray as an argument.
The function should be used as JSONArray.getJSONArray(0) which gets the first array of elements in your JSON data. You can put this in a loop to get all of them.
Example (taken from: http://art.buffalo.edu/coursenotes/art380/reference/JSONArray_getJSONArray_.html):
// The following short JSON file called "data.json" is parsed
// in the code below. It must be in the project's "data" folder.
//
// [
// [
// { "name": "apple", "isFruit": true },
// { "name": "grape", "isFruit": true },
// { "name": "carrot", "isFruit": false }
// ],
// [
// { "name": "lettuce", "isFruit": false },
// { "name": "plum", "isFruit": true },
// { "name": "cinnamon", "isFruit": false }
// ]
// ]
JSONArray json;
void setup() {
json = loadJSONArray("data.json");
// Get the first array of elements
JSONArray values = json.getJSONArray(0);
for (int i = 0; i < values.size(); i++) {
JSONObject item = values.getJSONObject(i);
String name = item.getString("name");
boolean isFruit = item.getBoolean("isFruit");
println(name + ", " + isFruit);
}
}
// Sketch prints:
// apple, true
// grape, true
// carrot, false
Second problem with your code is that you're declaring hourly_forecast twice: once globally and once within the responseReceived() function. You probably want to remove JSONArray from hourly_forecast within the responseReceived() function.

Resources