I have string response like this, I got only below response of my api.
{authToken: msadnmsandnasdn}
and I have to convert as below.
{"authToken": "msadnmsandnasdn"}
So how i can do this please Help me.
You can use various manipulation operations to do that manually:
import 'dart:convert';
void main() {
var s = "{authToken: msadnmsandnasdn, name:risheek}";
var kv = s.substring(0,s.length-1).substring(1).split(",");
final Map<String, String> pairs = {};
for (int i=0; i < kv.length;i++){
var thisKV = kv[i].split(":");
pairs[thisKV[0]] =thisKV[1].trim();
}
var encoded = json.encode(pairs);
print(encoded);
}
Output:
{"authToken":"msadnmsandnasdn"," name":"risheek"}
You need to use jsonDecode on that string like this:
var response = {authToken: msadnmsandnasdn....};
var result = jsonDecode(response);
Related
So when I get some string data from database I'm using this method
var res = "";
Future<void> cetak(String query) async {
var req = await SqlConn.readData(query);
setState(() {
res = req;
});
}
then im using method cetak() like this
cetak("SELECT CUST_NAME FROM ts_custxm WHERE CUST_CODE = '$custCode'");
But when im trying to display the res using Text(res)
it show [{"CUST_NAME":"MY NAME"}]
any idea how to make res only show MY NAME without show its column name?
You first need to convert by jsonDecode() or json.decode():
var req = jsonDecode(req)
setState(() {
res = req;
});
and then access to your data by:
res[0]["CUST_NAME"].toString()
You are getting result of a query in res variable. As a result of a query is an array of objects.
in your case : [{"CUST_NAME":"MY NAME"}]
so get MY NAME you should use res[0]["CUST_NAME"].toString().
Hope this will help!
I'm searching for create a dynamic form which contain DropDownButtons.
Before do that, I'm trying something on DartPad to know if it's possible to call a list with some Strings.
Below an example about what I want to do (maybe what I'm searching for is now possible) :
void main() {
List<Map<String, String>> listOf3AInitial = [{"name": "4A"},
{"name": "5A"}
];
String _listOf = "listOf";
String _year = "3A";
String _type = "Initial";
var listOfType = "$_listOf$_year$_type";
print(listOfType);
}
In this case it print "listOf3AInitial" and I want to print the List {"name": "4A"},{"name": "5A"}.
How it is possible to do that ?
Regards
You have to map a string of it's value to do so. For example
List<Map<String, String>> listOf3AInitial = [{"name": "4A"}, {"name": "5A"}];
Map<String, List<Map<String, String>>> list3AInitialMap = {
"listOf3AInitial" : listOf3AInitial,
};
Now you can get a value from this map like
String _listOf = "listOf";
String _year = "3A";
String _type = "Initial";
var listOfType = "$_listOf$_year$_type";
print(list3AInitialMap[listOfType]);
Your var listOfType returns a String. Unfortunately, you cannot use/convert String as a variable name.
In this case, you may want to use a map:
void main() {
List<Map<String, String>> listOf3AInitial = [{"name": "4A"},{"name": "5A"}];
List<Map<String, String>> listOf3BInitial = [{"name": "4B"},{"name": "5B"}];
String _listOf = "listOf";
String _yearA = "3A"; //A
String _yearB = "3B"; //B
String _type = "Initial";
//Reference your lists in a map
Map<String, dynamic> myLists = {
"listOf3AInitial": listOf3AInitial,
"listOf3BInitial": listOf3BInitial
};
//This returns your listOf3AInitial
var listOfType = myLists["$_listOf$_yearA$_type"];
print(listOfType);
//You may also access it directly
print(myLists["$_listOf$_yearB$_type"]);
}
metas: "["<p>1</p>","<p>2</p>","<p>3/p>","<p>4</p>"]"
to
List<String> metas = ["<p>1</p>","<p>2</p>","<p>3/p>","<p>4</p>"]
I can use it in JS JSON.parse (meta), is there any way to do it in dart?
Use could use the jsonDecode function from dart:convert
import 'dart:convert';
void main() {
var x = '["<p>1</p>","<p>2</p>","<p>3/p>","<p>4</p>"]';
List metas = jsonDecode(x);
print(metas); // [<p>1</p>, <p>2</p>, <p>3/p>, <p>4</p>]
print(metas[0].runtimeType); // String
}
I am using future builder for building list view. I am getting the response from server. I am getting exactly what i need. There is single error that i am trying to resolve. The error is when i fetch data from server using http.get method : String data=response.body; I am getting the right response that i want and i am parsing it as String catagoeryId=jsonDecode(data)["data"][i]["_id"];
Now the problem i faced when i decode this json i passed this String inside my constructor using for loop. But i have to give length to stop for loop. the length i am using is: data.length. It decode my json response and passes inside my constructor. But after the json length end its stop working and crashed. I checked the length of data.length its something around 344. But i am having only 3 objects. Here is the code i am using for parsing:
Future<List<ProductCatagoery>> getCatagories()async{
http.Response response = await http.get("http://138.68.134.226:3020/api/category/");
List<ProductCatagoery> products=[];
String data=response.body;
for (int i=0;i<=data.length;i++) {
String catagoeryId=jsonDecode(data)["data"][i]["_id"];
String catagoeryThumb=jsonDecode(data)["data"][i]["thumb"];
String catagoeryName=jsonDecode(data)["data"][i]["name"];
bool catagoeryActive=jsonDecode(data)["data"][i]["active"];
print('name is: $catagoeryId : $catagoeryThumb : $catagoeryName : $catagoeryActive');
ProductCatagoery newUser=
ProductCatagoery(catagoeryId,catagoeryThumb,catagoeryName,catagoeryActive);
products.add(newUser);
print('added ${newUser.id}');
print('length is${products.length}');
print('last length data: ${data.length}');
}
return products;
}
Model class:
class ProductCatagoery {
final String id;
final String thumb;
final String name;
final bool active;
ProductCatagoery(this.id,this.thumb,this.name,this.active);
}
Response is:
{"success":true,"data":[{"_id":"5f13cc94c63abc03522eff41","thumb":"category/fresh-meat.jpg","name":"Fresh Meat","active":true},{"_id":"5f13cc73c63abc03522eff40","thumb":"category/fruits-vegetables.jpg","name":"Fruits & Vegetables","active":true},{"_id":"5f13cca5c63abc03522eff42","thumb":"category/grocery.jpg","name":"Grocery","active":true}]}
Note: I just need String data=response.body; data length. I am not using an map etc. I also showed products in list if i return product list after 1, 2 or 3th iteration.
First, decode the response received
final responseFormat = json.decode(response.body);
Then, you can get the list you want to loop with this
final data = responseFormat["data"];
Finally, you can get the length of the list : data.length.
Full code
List<ProductCatagoery> products = [];
final responseFormat = json.decode(response.body);
final data = responseFormat["data"];
for (int i = 0; i < data.length; i++) {
String catagoeryId = data[i]["_id"];
String catagoeryThumb = data[i]["thumb"];
String catagoeryName = data[i]["name"];
bool catagoeryActive = data[i]["active"];
print(
'name is: $catagoeryId : $catagoeryThumb : $catagoeryName : $catagoeryActive');
ProductCatagoery newUser = ProductCatagoery(
catagoeryId, catagoeryThumb, catagoeryName, catagoeryActive);
products.add(newUser);
print('added ${newUser.id}');
print('length is${products.length}');
print('last length data: ${data.length}');
}
I have a Maps of type
Map<String,Map<String,bool>> outerMap;
Map<String,bool> innerMap_1 ,innerMap_2;
I need to nest innerMaps inside outerMap.
innerMap_1 = { 'time_1':true , 'time_2':false };
innerMap_1 = { 'time_3':false ,'time_4':true };
outerMap = { 'date_1':innerMap_1 , 'date_2':innerMap2 };
I need to store outerMap as a string on the Sqlite Database. When I try
jsonEncode(outerMap);
There is an error because it is nested.
How to effectively convert the outerMap to String and then convert that string back to Map ?
outerMap = { 'date_1':innerMap_1 , 'date_2':innerMap2 };
The thing is that you had a spelling error and therefore there was an error. But in my solution I fixed that.
Another thing to notice is that in order to use the jsonEncode function you have to import the dart:convert package.
import 'dart:convert';
void main() {
Map<String, Map<String, bool>> outerMap;
Map<String, bool> innerMap_1, innerMap_2;
innerMap_1 = {'time_1': true, 'time_2': false};
innerMap_2 = {'time_3': false, 'time_4': true};
outerMap = {'date_1': innerMap_1, 'date_2': innerMap_2};
String json = jsonEncode(outerMap);
print(json);
print(jsonDecode(json));
}
You can test your dart code on dartpad.dev.