flutter get json array - arrays

Hi I have this JSON as a string as a response for an API call
{
"friends": {
"data": [],
"summary": {
"total_count": 42
}
},
"id": "111111111111111"
}
I want to get friends.data and friends.summary.total_count.
Something like :
for (int i = 0 ; i < friends.summary.total_count ; i++)
{
myAmazingArray.pushback(friends.data[i]);
}
I think that total_count is the number of contents in the array.
I also know that in order to get the "id" I have to do : json['name']

You need to use jsonDecode from dart:convert. Actually you don't even need to use the total_count value at all, if the length in data is the same. You can simply use:
import 'dart:convert';
final Map<String, dynamic> dataMap = jsonDecode(json);
final List<dynamic> friendsData = dataMap['friends']['data'];
for(dynamic friend in friendsData) myAmazingArray.pushback(friend);
I don't know what kind of content is contained in data, so I suggest you to find out the runtime type (e.g. String, Map etc.) and exchange the word 'dynamic' in my code above to improve the code quality.
If you wanted to do it with total_count:
final int total_count = dataMap['friends']['summary']['total_count'];
for(int i=0; i<total_count; i++)
myAmazingArray.pushback(friendsData[i]);

Related

Cannot pass a string array from external data file postman automation scripts

I'm trying to pass a string array in postman- post request
postman request- body
{
"fruits":[{{fruits}}],
}
postman- test
var fruits=["mango","apple","orange"]
for (let i = 0; i < 3; i++) {
fruits.push(jsonData.fruits.toString());
}
pm.globals.set("fruits", fruits);
Then set fruits as global variables
Then run the API through the collection runner with the external data file. Then check the response body and I got this
got a 404 error
If anyone can let me know how to pass a array as a string in postman. When we pass a string array it will defined as a ascii value. So this issue has happened. So please guide me through this.
First, if you want to save an array as a variable, remember to stringify this.
let fruits=["mango","apple","orange"]
pm.globals.set("fruits", JSON.stringify(fruits));
Second, you don't need to add [ ] in request body, just put the variable
{
"fruits": {{fruits}}
}
Result:
{
"fruits": ["mango","apple","orange"]
}

Req.files to hold file objects in multiple arrays

What I am building allows user's to create groups and within each group hold files. I have this set up but am having trouble looping through the files within the group on my server side (express js).
Before I send to my server I build my formData like this
// loop through groups
for(var i = 0; i < data.groups.length; i++) {
formData.append('groups[]', data.groups[i])
// loop through photos in group
for(var s = 0; s < data.groups[i].length; s++) {
formData.append('photos[]', data.groups[i][s])
}
}
Now on my server side groups can be looped through. However with Multer as my middleware my photos aren't being received in arrays. My files come in as objects within one array in req.files. So instead of having groups[0]/req.files[0] with 2 files and groups[1]/req.files[1] with 1 file. I have groups[0] with 2 files and req.files[0] with 3 files making it difficult to match the groups with their respected photos.
Any idea how I can get my req.files to hold array's instead of every file in an object such as...
[
[ { file }, { file } ],
[ { file } ]
]
// rather than
[
{
file
},
{
file
},
{
file
}
]
** am leaning towards upload.fields() in attempts at a solution but haven't worked it out yet
You need to add the group index to the field name:
// loop through groups
for(var i = 0; i < data.groups.length; i++) {
// loop through photos in group
for(var s = 0; s < data.groups[i].length; s++) {
var fieldname = 'photos[' + i + '][]';
formData.append(fieldname, data.groups[i][s])
}
}
But the problem is that the multer does not process the nested arrays (PHP's naming conventions). So pay attention to other middleware, for example on express-form-data.

Unable to access first data item in JSON Array

I'm having trouble pulling a piece of data from a JSON array. I believe I've tried every answer from similar posts here but I'm missing something. I've imported the org.JSON library. Here is my JSON text:
{
"symbol":"AAPL",
"earnings":[
{
"actualEPS":2.34,
"consensusEPS":2.17,
"estimatedEPS":2.17,
"announceTime":"AMC",
"numberOfEstimates":10,
"EPSSurpriseDollar":0.17,
"EPSReportDate":"2018-07-31",
"fiscalPeriod":"Q3 2018",
"fiscalEndDate":"2018-06-30",
"yearAgo":1.67,
"yearAgoChangePercent":0.40119760479041916,
"estimatedChangePercent":0.29 940119760479045,
"symbolId":11
},
{
"actualEPS":2.73,
"consensusEPS":2.69,
...
...
}
]
I'm trying to read the first instance of "actualEPS", there are a total of four in the array. My code currently looks like this:
String jsonIn = sb.toString();
JSONArray earningsArray = new JSONArray(jsonIn);
double eps = 0;
for(int i = 0; i < earningsArray.length(); i++) {
JSONObject jObject = earningsArray.getJSONObject(i);
eps = jObject.getDouble("actualEPS");
} // end for loop
System.out.println("This is the first instance of EPS: " + eps);
The StringBuilder (sb) in the first line is my JSON and prints out correctly in the console just ahead of this block.
The stack trace shows the error in this line:
JSONArray earningsArray = new JSONArray(jsonIn);
The error I'm getting is
"A JSONArray text must start with '[' at 1 [character 2 line 1]"
I've never used JSON prior to now and am not sure what my error is exactly. I tried shortening the String going into the array to begin with just the array opening bracket but that didn't work either. I feel like I'm missing something simple. Where have I gone wrong?
You need to understand there are two types of datastructure in a JSON.
first is Object which always starts with '{' and ends with '}'
second is Array which always starts with '[' and ends with ']'
JsonArray is nothing but an array of JsonObject means a json array will always look like
"jsonarray":[
{
//json object
},
{
// json object
}
]
hope now you understand how json works
now come to your json
{ // jsonObjectParent Starts
"symbol":"AAPL",
"earnings":[ // jsonArray Starts
{ //jsonObject1 Starts
"actualEPS":2.34,
"consensusEPS":2.17,
"estimatedEPS":2.17,
"announceTime":"AMC",
"numberOfEstimates":10,
"EPSSurpriseDollar":0.17,
"EPSReportDate":"2018-07-31",
"fiscalPeriod":"Q3 2018",
"fiscalEndDate":"2018-06-30",
"yearAgo":1.67,
"yearAgoChangePercent":0.40119760479041916,
"estimatedChangePercent":0.29 940119760479045,
"symbolId":11
}, // jsonOject1 Ends
{ //jsonObject2
"actualEPS":2.73,
"consensusEPS":2.69,
...
...
}
] //jsonArray Ends
} //jsonObjectParent Ends
So here if you want to parse this json you have to first parse it in a jsonObject as you seen above
JsonObject jsonObjectParent = new JsonObject(jsonIn);
// here jsonobject contains json array so etract it like this
JsonArray jsonArray = jsonObjectParent.getJsonArray("earnings");
//now you can access the values here
JsonObject jsonObject1 = jsonArray.getJsonObject(0); // here 0 means first jsonObject in array if you want all you can make a loop here
string actualEps = jsonObject1.getDouble("actualEPS");
Hope now you understands the concept of how JSON Works
please let me know is this solution worked
Do this :
JSONObject json = new JSONObject(response);
JSONArray data = json.optJSONArray("earnings");
for (int i = 0; i < data.length(); i++) {
JSONObject jsonObject1 = data.getJSONObject(i);
Double actualEPS = jsonObject1.getDouble("actualEPS");
Double consensusEPS = jsonObject1.getDouble("consensusEPS");
Double estimatedEPS= jsonObject1.getDouble("estimatedEPS");
String announceTime = jsonObject1.getString("announceTime");
int numberOfEstimates = jsonObject1.getInt("numberOfEstimates");
Double EPSSurpriseDollar= jsonObject1.getDouble("EPSSurpriseDollar");
String EPSReportDate= jsonObject1.getString("EPSReportDate");
String fiscalPeriod= jsonObject1.getString("fiscalPeriod");
String fiscalEndDate= jsonObject1.getString("fiscalEndDate");
Double yearAgo= jsonObject1.getDouble("yearAgo");
Double yearAgoChangePercent= jsonObject1.getDouble("yearAgoChangePercent");
Double estimatedChangePercent = jsonObject1.getDouble("estimatedChangePercent");
int symbolId = jsonObject1.getInt("symbolId");
}
#Driver8, the JSON earninsArray is a single JSON object and not an array of JSON objects. Your basic idea here is alright everywhere excpet for just that line. Instead of instantiating a JSON array, instantiate a JSON OBJECT.
Should be something like this:
String jsonIn = sb.toString();
JSONObject earningsObject = new JSONObject(jsonIn);
JSONArray earningsArray = earningsObject.getJSONArray("earnings");
double eps = new double(earningsArray.length());
for (int i = 0; i < earningsArray.length(); i++) {
JSONObject j1 = earningsArray.getJSONObject(i);
eps[i] = j1.getDouble("actualEPS");
}
All the values of actualEPS will be stored as per their order in the array declared to store the EPS values.
Hope this helps.

Extracting Array inside a Property in Azure Stream Analytics

I have had no luck so far extracting certain values in a wide format out of a JSON string via a stream analytics job.
The JSON has the following format:
{"devicename":"demo","msgtime":"2018-04-13T11:00:00.0000000Z",
"payload":[{"Sensor":"one","Value":1.817,"Unit":"W"},
{"Sensor":"two","Value":0.481,"Unit":"W"},
{"Sensor":"three","Value":0.153,"Unit":"W"}]}}
I am trying to get it in the following format:
name one two three
demo 1.817 0.481 0.153
… … … …
I tried getting the values with "Cross APPLY GetPropertyValues(input)", but I can't get them in a wide format.
try code like below
SELECT
localInput.devicename,
udf.getValue('one', localInput.payload) as One,
udf.getValue('two', localInput.payload) as Two,
udf.getValue('three', localInput.payload) as Three
FROM localInput;
function main(identifier, arr) {
var result = null;
if (Object.prototype.toString.call(arr) == "[object Array]") {
for (i = 0; i < arr.length; i++) {
if (arr[i].type == identifier) {
result = arr[i].value;
}
}
}
return result;
}

parse json arrays using cJSON library

First off, this is a very broad question, and it might come across as me asking for the community to write my code for me. That is not my intent, but I am so lost, I don't know how to give enough information.
I am attempting to use the cJSON library, written by Dave Gamble,
I found this is very useful to use for my embedded device for JSON parse and composing.
to read in the following JSON array
{
"name": "Jack",
"types":[23,56,78],
"format": {
"type": "rect",
"width": 1920, }
}
.. and parsing the getting the object worked with this method
cJSON *format = cJSON_GetObjectItem(json,"format");
int framerate = cJSON_GetObjectItem(format,"width")->valueint;
but I am not able to parse the key "name" and object simple key value ,
I tried this
cJSON *array = cJSON_GetArrayItem(json,"types");
int value = cJSON_GetArrayItem(format1,1)->valueint;
but did not work, how to parse the array object and simple key value..
Your json is just fine. You can iterate through array of values in cJSON:
cJSON * array = cJSON_GetObjectItem(json, "types");
for (i = 0 ; i < cJSON_GetArraySize(array) ; i++)
{
printf("%d ",cJSON_GetArrayItem(array, i)->valueint);
}
will print
23 56 78
I think JSON element should respect key:value format.
{
"name": "Jack",
"types":[{"type" : 23}, {"type" : 56}, {"type":78}],
"format": {
"type": "rect",
"width": 1920, }
}

Resources