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"];
Related
"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));
}
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;
}
I am trying to iterate through a value (that is a hashMap) of a JSONObject.
First I get a server response that is a String.
Then I turn it into a String! like this:
val responseString = response.serverResponse
Then I turn it into a JSONObject like this:
val jsonObj = JSONObject(responseString.toString()).get("data")
I do the second step because I only want to keep the LinkedHashMap shown in the picture attached.
But the second step returns type "Any" and then I cant iterate through the LinkedHashMap
JSONObject myjsonObject = new JSONObject();
Iterator keyvalues = jsonObject.keys();
while(keys.hasNext()) {String key = keyvalues.next();
if (myjsonObject.get(key) instanceof myjsonObject) {
}
}
I've managed to extract data from a POST method in hyper using the following:
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Method, Request, Response, Server};
use std::convert::Infallible;
use std::net::SocketAddr;
use tokio;
async fn handle(_req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
match (_req.method(), _req.uri().path()) {
(&Method::GET, "/") => Ok(Response::new(Body::from("this is a get"))),
(&Method::POST, "/") => {
let byte_stream = hyper::body::to_bytes(_req).await?;
let _params = form_urlencoded::parse(&byte_stream)
.into_owned()
.collect::<HashMap<String, String>>();
However, the whole JSON body is just one key in the HashMap now. How do I split it up so I have a hashmap with multiple keys and values as opposed to one key that's the entire body?
[dependencies]
futures = "0.1"
hyper = "0.13"
pretty_env_logger = "0.3.1"
url = "2.1.1"
tokio = { version = "0.2", features = ["macros", "tcp"] }
bytes = "0.5"
There is a discrepancy between your description:
However, the whole JSON body
And your code:
let _params = form_urlencoded::parse(&byte_stream)
If your data is JSON then parse it as JSON, using the serde_json crate:
let _params: HashMap<String, String> = serde_json::from_slice(&byte_stream).unwrap();
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