Flutter : How to get value in Object JSON? - arrays

Good healty everyone, I want to ask something about managing data from JSON. I've JSON format like below :
{
"msg": "Success"
"data": [
{
"id": "1",
"notelp": "0000000000",
"user": "no1"
},
{
"id": "2",
"notelp": "1111111111",
"user": "no2"
},
],}
and I want to get value from variable "notelp", I expect output like this {"0000000000", "1111111111",} how to get it ?
I tried this before, but still can't get what I want,
if (response.statusCode == 200) {
final result = json.decode(response.body);
debugPrint('dataTelp: ${result['data']['notelp']}');
}
thank you guys to help me to solve it and stay save.

You can use the forEach or another looping method to get data from a list.
List outPut = [];
List data = response['data'];
data.forEach((element) {
outPut.add(element['notelp']);
});
print(outPut);

Related

Converting a typescript class object with dictionary to a JSON array

After some digging I decided my backend needed to consume duplicate keys and as a consequence my frontend can no longer send a dictionary as a JSON string.
See my previous question.
After applying the solution provided
let mediatagRequest = new MediaTagRequest(tags);
const headers = { 'content-type': 'application/json' }
let jsonObject = {};
for (let entry of mediatagRequest.tags.entries())
{
jsonObject[entry[0]] = entry[1];
}
const body = JSON.stringify({
tags: jsonObject
});
My current output (which is what I then wanted)
{
"tags": {
"city": "Karachi"
}
However my needs have changed and after a bit of of struggle I couldn't get my desired output to be like this
{
"tags": [
{
"key": "city",
"value": "Karachi"
},
{
"key": "city",
"value": "Mumbai"
}
]
}
Could someone help, thank you.
To get your desired output you could use the Object.entries() function to get the key, value pairs separately. This code segment will turn an object into a list of objects with key value pairs:
test_object = {
karachi: "dubai",
mumbao: "moscow",
};
output = Object.entries(test_object).map(([key, value]) => ({ key, value}));
console.log(output);
You can adapt this code to select the desired parts of your object and format them as you like. There are other Object functions you can see in the documentation.

How to read objects and store into array

I made an http request and got back e.g the below json. I want to read the cars and the shoes objects into separate arrays at the time of the http request.
json
{
"id": 9,
"name": "Zlatan",
"cars": [
{
"type": "ford",
"year": "2019"
},
{
"type": "audi",
"year": "2017"
}
]
"shoes": [
{
"brand": "adidas",
"status": "old"
},
{
"brand": "timberland",
"status": "new"
}
]
}
comp.ts
cars = [];
shoes = [];
//......
getZlatan() {
return this.httpService.getInfo()
.subscribe( data => {
this.objZlatan = data; //this part holds the json obj above
this.cars ....//what to add here
this.shoes ....// here too.
} );
}
Or is there a cleaner way to load the arrays at http request?
Access the cars and shoes properties of the data with simple dot-notation. It might be ideal to check if the data returned is not null with if(condition here) and then perform your logic. If you have more objects and want to bring all cars and shoes under one array then you have to loop through.
getZlatan() {
return this.httpService.getInfo()
.subscribe(data => {
this.objZlatan = data;
this.cars = this.objZlatan.cars;
this.shoes = this.objZlatan.shoes;
});
}
Just use . and type names to access cars and shoes. Let me show an example:
return this.httpService.getInfo()
.subscribe( data => {
this.objZlatan = data; //this part holds the json obj above
this.cars = data.cars;
this.shoes =data.shoes;
} );

ROKU: Associative Array with multiple values

I have a 2 part question that I am hoping someone can help me with.
I am trying to figure out how to pass an array of years from my server to my ROKU code. It is going to be a variable number of years, meaning there won't always be the same number of elements in the array.
What I need to figure out is how to set up the array, and then how to parse it in BrightScript.
Here is an example of what I have so far. I have the count, but still need to add all the years.
The list of years is 1998,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014
{
"Items" : [
{
"name": "count",
"value": "13"
}
]}
Once it's received in my ROKU code, I will need to loop over the years, and display them, one per line. (I already have the display part done. I just need help knowing how to get at the array elements.)
Since there is so little useful documentation out there for BrightScript arrays, I'm hoping someone with more experience will be able to answer this, and that it will help someone else in the future.
You don't need to do any of that. Just send the JSON array and Roku will parse it:
BrightScript Debugger> myJSON = "[1998,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014]"
BrightScript Debugger> ? type(myJSON)
String
BrightScript Debugger> arr = parseJSON(myJSON)
BrightScript Debugger> ? type(arr)
roArray
It's perfectly valid to have array as top-level element of the json text ("A JSON text is a serialized object or array." per RFC 4627). You can also do it with a dummy object (but why?):
arr = parseJSON(" {"years": [1998, 2003]} ").years
Here is how I solved it:
Array:
{
"Items" : [
{ "value": "2014" } ,
{ "value": "2013" } ,
{ "value": "2012" } ,
{ "value": "2011" } ,
{ "value": "2010" } ,
{ "value": "2009" } ,
{ "value": "2008" } ,
{ "value": "2007" } ,
{ "value": "2006" } ,
{ "value": "2005" } ,
{ "value": "2004" } ,
{ "value": "2003" } ,
{ "value": "1998" }
]
}
BrightScript code to parse it:
arr = CreateObject("roArray",json.Items.count(),false)
for each item in json.Items
thisItem = {
value: item.value
}
arr.push(thisItem)
end for
return arr
I hope this helps someone else in the future.

How do i compare an as3 string with a json array?

Im trying to compare two specific bits of information. One is in the form of a as3 string the other is in the form of a Json array.
The Json array shows customer data from a shop website. What i want to do is have as3 compare the string(i.e a customer name) with the data , and when it has found the matching name, only trace that customers specific information.
Im amusing id have to use a loop for the comparison , but im having trouble getting my head around how to convert the Json into specific junks that can then be compared individually with a string. Any help would be perfect.
Thanks
Be aware that JSON is just a standard AS3 object. There's no magic going on here; loop through it as you would any other structure and run your comparisons as usual.
Solution
var jsonObj:Object = {
"customers": [
{
"id": "04aa1ab3-521b-11e3-a29a-bc305bf5da20",
"name": "fake name",
"customer_code": "00000002",
"customer_group_id": "6012cd22-5166-11e3-a29a-bc305bf5da20",
"customer_group_name": "All Customers",
"first_name": "test",
"last_name": "test",
"company_name": "",
"email": "testest#yahoo.com"
}
]
}
var myString:String = "fake name";
for (var k:String in jsonObj.customers[0]) {
var v:String = jsonObj.customers[0][k];
if (v == myString) {
trace(myString + "'s email is " + jsonObj.customers[0].email)
}
}
Use a Dictionary Object to store customer objects using their unique names (or ids ) as reference;
You certainly do not want to write unnecessary loop search for a customer in question.
Solution.
var jsonObj:Object = {
"customers": [
{
"id": "04aa1ab3-521b-11e3-a29a-bc305bf5da20",
"name": "fake name",
"customer_code": "00000002",
"customer_group_id": "6012cd22-5166-11e3-a29a-bc305bf5da20",
"customer_group_name": "All Customers",
"first_name": "test",
"last_name": "test",
"company_name": "",
"email": "testest#yahoo.com"
}
]
}
//Dictionary Object to store customers
var customers:Dictionary=new Dictionary();
//customer object in the json
var customer:Object;
//loop json object to retrieve customers and
//store them in Dictionary using either unique name or id
for each(customer in jsonObj)
customers[customer.name]=customer;
//retrieve customer in question
function getCustomer(id:String):Object
{
return customers[id] as Object;
}

ExtJs root node

What is the root property value if I get a Json like that:
{
"status": {
"status": 0,
"msg": "Ok",
"protocolversion": "extjs.json"
},
"value": {
"table": [
[
"admin",
"Administrator",
""
],
[
"test",
"Test",
""
]
],
"total": 2
}
}
The data will be displayed in a gridpanel, 1 row is admin, 1 row is test, etc.
Tried:
value, value.table
How to get this to work?
value.table is correct for the root property, but you are using a json format that I don't think Ext is set up to handle by default. It has a reader for json that is used for an array of objects, not for an nested arrays of field values with no object mapping information.
If you have to use that format, you will either need to create your own readers/writers or just use Ext.Ajax.request(), and in the callback, parse the nested array into objects. Something like:
Ext.Ajax.request({
url: 'path.com/to/content',
success: function (response, operation) {
var data = Ext.JSON.decode(response.responseText);
var fields = data.value.table;
var records = [];
Ext.Array.each(fields, function (fieldArray, fieldIndex) {
Ext.Array.each(fieldArray, function(fieldValue, valueIndex) {
//Create record object if it doesn't exist
var record = records[valueIndex] || {};
//Create a switch statement based on the array index to set fields
switch(fieldIndex) {
case 0:
record.User_id = fieldValue;
break;
case 1:
record.Username = fieldValue;
break;
}
});
});
//Add the objects to the empty store
store.add(records);
}
});
That's not a production solution by any means since it doesn't handle that empty string at the end of your list or the case that you get a jagged array of arrays per field which I can't imagine what to do with. If it's within your control or influence, I would suggest using a format more like what Ext suggests so you can use the built in json proxy/reader/writer or go crazy with it and implement ext's remote procedure call format:
{
"success": true,
"message": "Success",
"data": [
{
"User_id": "admin",
"Username": "Administrator"
}, {
"User_id": "admin",
"Username": "Administrator"
}
]
}
In above example "value" is root property. But for JSON reader it's a property name (or a dot-separated list of property names if the root is nested).
so you can assign into your field you need following.
fields:['table.admin','table.test']

Resources