Extract Data from JSON Array in Flutter/Dart - json

This is the response from request.
var response = [{"id":4731},{"id":4566},{"id":4336},{"id":4333},{"id":4172},{"id":4170},{"id":4168},{"id":4166},{"id":4163},{"id":4161}];
How to extract ids and store in List of int using flutter.
I have try this code but not working.
Future<List<int>> fetchTopIds() async{
final response = await client.get('$_baseUrl/posts?fields=id');
final ids = json.decode(response.body);
return ids.cast<int>();
}

This should do what you want:
var intIds = ids.map<int>((m) => m['id'] as int).toList();

This is what I did when got "array of object" as response (I know I'm late. But it will help the next guy)
List list = json.decode(response.body);
if (response.body.contains("id")) {
var lst = new List(list.length);
for (int i = 0; i < list.length; i++) {
var idValue = list[i]['id'];
print(idValuee);
}

Here I attached a complete example of converting a list to JSON and then retrieve the List back from that JSON.
import 'dart:convert';
void main() {
List<int> a= [1,2,3]; //List of Integer
var json= jsonEncode(a); //json Encoded to String
print(json.runtimeType.toString());
var dec= jsonDecode(json); //Json Decoded to array of dynamic object
print(dec.runtimeType.toString());
a= (dec as List).map((t)=> t as int).toList(); //dynamic array mapped to integer List
print(a);
}

I found a better and easier way to get required information/ data from JSON Array.
Refer to https://pub.dev/packages/http/example to know more
Code to get a quick starts:
void main(List<String> arguments) async {
var url = 'ENTER YOUR API ENDPOINT';
var response = await http.get(url);
var jsonResponse = convert.jsonDecode(response.body);
var itemCount = jsonResponse['totalItems'];
print('Number of books about http: $itemCount.');
Here 'totalItems' would be your desired key.This will only work if you get a response.statusCode == 200

Related

I'm trying to make a simple app in flutter that fetches data from an API. However when I try running the code I get the following error

"Dart Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable' "
It says that the error is in the following line:
for(var jsonObject in jsonObjects){
objects.add(Object.fromJson(jsonObject));
}
For context, the entire code is this:
class _HomePageState extends State<HomePage> {
final List<Object> _objects = [];
Future<List<Object>> fetchData() async{
const String urlString = 'https://api.publicapis.org/entries';
final Uri url = Uri.parse(urlString);
var response = await http.get(url);
final List<Object> objects = [];
if(response.statusCode == 200){
var jsonObjects = json.decode(response.body);
print("Step 1");
for(var jsonObject in jsonObjects){
objects.add(Object.fromJson(jsonObject));
}
}
return objects;
}
Any help would be greatly appreciated. Thanks.
Main problem is that response.body is not a list of elements, and you are assuming it is. Instead of that, it's a "key" : "value" type of json object, which cannot be iterated.
The for (var e in collection) syntax is made to be used with an Iterable collection, and _InternalLinkedHashMap (and maps in general) are not iterables.
The solution is to parse the response properly. Check this link if you want to follow best practices for flutter development json parsing.
Your api response's body is a Map:
{"count":1425,
"entries":[
{"API":"AdoptAPet","Description":"Resource to help get pets adopted","Auth":"apiKey","HTTPS":true,"Cors":"yes","Link":"https://www.adoptapet.com/public/apis/pet_list.html","Category":"Animals"},
{"API":"Axolotl","Description":"Collection of axolotl pictures and facts","Auth":"","HTTPS":true,"Cors":"no","Link":"https://theaxolotlapi.netlify.app/","Category":"Animals"},
...
]
}
what you are looking for is a list, Try this:
var jsonObjects = json.decode(response.body["entries"]);
print("Step 1");
for(var jsonObject in jsonObjects){
objects.add(Object.fromJson(jsonObject));
}

How to use azure function to read a json file url or a url text file that has json data into string?

public static async Task<string> MakeSlackRequest(string message)
{
var urlJsonData = "{'text':'message'}"; // I want my url with json data to convert into jsonstring
using(var client = new HttpClient())
{
var requestData = new StringContent("" + urlJsonData.ToString(), Encoding.UTF8, "application/json");
var response = await client.PostAsync($"webhookURL", requestData);
var result = await response.Content.ReadAsStringAsync();
return result;
}
}
I have a url file(jsonData.json and jsonData.txt), anyone know how to convert a url file with jsonData.json or jsonData.txt into a string for azure function?
Use this code
var urlJsonData = client.GetStringAsync("url/sample.json").Result;

How to return list in Dart language

I my code I want to return categories name list and populate in list view by using dart. i use HTTP get request and can successfully print the Json data but when I loop the json data into list but it cannot and print(categoriesList.length); give me no result. any idea how to solve it
Future<List<Categories>> _getCategory() async {
var data = await http.get("https://thegreen.studio/ecommerce/E-CommerceAPI/E-CommerceAPI/AI_API_SERVER/Api/Category/ViewCategoryNameAPI.php");
var jsonData = json.decode(data.body);
print(jsonData);
List<Categories> categoriesList = [];
for(var c in jsonData)
{
Categories a = Categories(c["Name"]);
categoriesList.add(a);
}
print(categoriesList.length);
return categoriesList;
}

Parsing using For in String jsonString = await _ChieseAsset();

Yo ,, during my experience of flutter i'll try to show on map marker saved into Json file..in this way i retrive only one of row
Future<chiese> loadChiese() async {
await wait(5);
String jsonString = await _ChieseAsset();
final jsonResponse = json.decode(jsonString);
for ( var i=0; i < 5; i++ ){
print(i);
return new chiese.fromJson(jsonResponse[i]);
}
}
Unfortunally var i show only 0 value and don't scan into json retrive only first value
why???
if i use ...
Future<chiese> loadChiese() async {
await wait(5);
String jsonString = await _ChieseAsset();
final jsonResponse = json.decode(jsonString);
return new chiese.fromJson(jsonResponse);
}
Reciving error ...
[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: type 'List' is not a subtype of type 'Map'
Any idea??? Thanks
Change this:
return new chiese.fromJson(jsonResponse);
Into this:
return new chiese.fromJson(jsonResponse[0]);

get value from json with dynamic key

My JScript is:
var t={'color':'red'}; // dynamic json data.
for(n in t)
{
alert(n)
}
here, alert gives the json key color. but how to get its value?
Note: the json is dynamic.
var t={'color':'red'}; // dynamic json data.
for(n in t)
{
alert(n);// n = key
var val =t[n];// value where key is n
}
Here is a simple example to get dynamic keys from json response - Get dynamic keys from JSON Data
public void getData(String data){
// Load json data and display
JSONObject jsonData = new JSONObject(data);
// Use loop to get keys from your response
Iterator itr = jsonData.keys();
while(itr.hasNext()){
String keys = (String)itr.next();
Log.e("Keys", "----"+keys);
JSONArray dynamicValue = jsonData.getJSONArray(keys);
// Your stuff here
} }
var t={'color':'red'}; // dynamic json data.
for(n in t)
{
alert(t[n])
}
instead of putting the n in al alert put it in an external variable or something...
Edited, try sometnihg like this:
var ex_n;
var t={'color':'red'};
for(var i=0; i<t.length; i++) ex_n = t[i]["color"];