Processing error message 'The function getJSONArray(JSONArray) does not exist' - arrays

i am not sure why i am getting the error message 'The function getJSONArray(JSONArray) does not exist' when i run this sketch that uses a json query to Weather Underground. That comment seems illogical since Processing is recognising the id ref for the JSONArray.
The .json can be read here: http://api.wunderground.com/api/97a2805510de59e9/hourly/q/pws:IENGLAND274.json
Any thoughts? Thanks.
import com.francisli.processing.http.*;
HttpClient client;
String data;
com.francisli.processing.http.JSONObject weatherInfo;
JSONArray hourly_forecast;
int last = 0;
PImage img;
Float humidity = 50.2;
void setup() {
size(700, 700);
client = new HttpClient(this, "api.wunderground.com");
client.GET("/api/97a2805510de59e9/hourly/q/pws:IENGLAND274.json");
background(255);
}
void responseReceived(HttpRequest request, HttpResponse response) {
println(response.getContentAsString());
weatherInfo = response.getContentAsJSONObject();
JSONArray hourly_forecast = weatherInfo.getJSONArray(hourly_forecast);
}

There is no method called getJSONArray() that takes in a JSONArray as an argument.
The function should be used as JSONArray.getJSONArray(0) which gets the first array of elements in your JSON data. You can put this in a loop to get all of them.
Example (taken from: http://art.buffalo.edu/coursenotes/art380/reference/JSONArray_getJSONArray_.html):
// The following short JSON file called "data.json" is parsed
// in the code below. It must be in the project's "data" folder.
//
// [
// [
// { "name": "apple", "isFruit": true },
// { "name": "grape", "isFruit": true },
// { "name": "carrot", "isFruit": false }
// ],
// [
// { "name": "lettuce", "isFruit": false },
// { "name": "plum", "isFruit": true },
// { "name": "cinnamon", "isFruit": false }
// ]
// ]
JSONArray json;
void setup() {
json = loadJSONArray("data.json");
// Get the first array of elements
JSONArray values = json.getJSONArray(0);
for (int i = 0; i < values.size(); i++) {
JSONObject item = values.getJSONObject(i);
String name = item.getString("name");
boolean isFruit = item.getBoolean("isFruit");
println(name + ", " + isFruit);
}
}
// Sketch prints:
// apple, true
// grape, true
// carrot, false
Second problem with your code is that you're declaring hourly_forecast twice: once globally and once within the responseReceived() function. You probably want to remove JSONArray from hourly_forecast within the responseReceived() function.

Related

How to iterate JSON objects

How can I iterate a json object and get it's values in dart.
Below is an Example json object that is want to get it's value.
"SomeJsonList": {
"image": ["imageUrl1", "imageUrl2"],
"video": ["videoUrl1", "videoUrl2"]
}
To get the values of the image and video object as a list.
The output i am looking for:
var urlList = [];
urlList = [imageUrl1, imageUrl2,videoUrl1,
videoUrl2]
You can merge list items using addAll as below
void main() {
Map<String, List<String>> json = {
"image": ["imageUrl1", "imageUrl2"],
"video": ["videoUrl1", "videoUrl2"]
};
List<String>? img = json["image"];
List<String>? vid = json["video"];
List<String> list = [];
list.addAll(img!); // better check if `img` not null instead of "!"
list.addAll(vid!); // better check if `vid` not null instead of "!"
// list.addAll(xyz); // some more if needed
print(list); // [imageUrl1, imageUrl2, videoUrl1, videoUrl2]
}

How to parse JSON response which contains nested JSON array

I'm trying to parse a JSON response from an API and store the data to DATA CLASS and sending the data to recycler adapter as ArrayList.
The JSON Array has another array of objects inside, and I'm not able to find a way to properly parse that JSON response.
Here is my data class:
data class OrderDetails (
val orderId: String, // order_id value from json object goes here //
val restaurantName: String, // restaurant_name value from json object goes here //
val totalCost: String, // total_cost value from json object goes here //
val orderDate: String, // order_placed_at value from json object goes here //
val orderFoodDetails: String // food_items value in json response is an array and i'm stuck here //
)
Here is my Kotlin code:
try {
val data = it.getJSONObject("data")
val success = data.getBoolean("success")
if (success) {
val arrayData = data.getJSONArray("data")
for (i in 0 until arrayData.length()) {
val orderJsonObject = arrayData.getJSONObject(i)
val orderObject = OrderDetails(
orderJsonObject.getString("order_id"),
orderJsonObject.getString("restaurant_name"),
orderJsonObject.getString("total_cost"),
orderJsonObject.getString("order_placed_at"),
orderJsonObject.getJSONArray("food_items").toString() // getting array and storing as a string
)
orderList.add(orderObject)
for (orders in orderList) {
val foodData = orders.orderFoodDetails
val jsonFood = JSONArray(foodData)
for (j in 0 until jsonFood.length()) {
val foodJsonObject = jsonFood.getJSONObject(j)
val foodObject = OrderFoodDetails(
foodJsonObject.getString("food_item_id"),
foodJsonObject.getString("name"),
foodJsonObject.getString("cost")
)
ordersFood.add(foodObject)
}
}
}
Here is the Json response:
{
"data": {
"success": true,
"data": [
{
"order_id": "17790",
"restaurant_name": "Rotten Tomatoes",
"total_cost": "280",
"order_placed_at": "02-11-20 19:00:54",
"food_items": [
{
"food_item_id": "156",
"name": "Rotten Bhajiya",
"cost": "100"
},
{
"food_item_id": "155",
"name": "Rotten Salad",
"cost": "100"
},
{
"food_item_id": "154",
"name": "Rotten Soup",
"cost": "80"
}
]
},
Required Output
Prefered Output
My output
my current output
do you tried to use GSON or Moshy lib ?
This case will be easier solved with one of this :)
If you don't want to use one of them, just try to replace your for cycle to map or for each, to make it more readable. Looks like you make it right, but can you check the result of try catch block please?

Why am I getting org.json.JSONException: Not a primitive array?

I have this function:
fun getFeed(token: String): Result<Array<Post?>, Exception> {
if (token != "") {
val (request, response, result) = "https://alles.cx/api/feed"
.httpGet()
.header("Authorization", token.toString())
.response()
when (result) {
is Result.Success -> {
println("Result success")
try {
val responseJSON = JSONObject(String(response.data))
if (!responseJSON.has("err")) {
println("Has no error")
var feedArray = arrayOfNulls<Post>(0)
println("HERE?")
var feed = JSONArray(responseJSON["feed"]) // <-----ERROR HERE
println("not here")
println("Made to the for")
for (i in 0 until feed.length()) {
println("For $i")
val jsonObject = feed.getJSONObject(i)
var imageURL: URL? = null
if (jsonObject.has("image")) {
imageURL = URL(jsonObject["image"].toString())
}
feedArray[i] = Post(
jsonObject.getString("id"),
User(jsonObject.getJSONObject("author").getString("id"), jsonObject.getJSONObject("author").getString("username"), jsonObject.getJSONObject("author").getString("name")),
jsonObject.getString("createdAt"),
jsonObject.getInt("replyCount"),
jsonObject.getInt("score"),
jsonObject.getString("content"),
null,
imageURL,
jsonObject.getInt("vote")
)
println("Added post $i")
}
println(feedArray)
return Result.Success(feedArray)
}
else {
println("yes error")
return Result.Failure(Exception(responseJSON["err"].toString()))
}
}
catch(e: Exception) {
return Result.Failure(e)
}
}
is Result.Failure -> {
return Result.Failure(Exception(result.component2()?.localizedMessage))
}
}
}
else {
return Result.Failure(Exception("badAuth"))
}
}
An error is occurring on this line. I know this because of the print statements that are in the code:
var feed = JSONArray(responseJSON["feed"]) // <-----ERROR HERE
This is what the error that is occurring is.
[Failure: org.json.JSONException: Not a primitive array: class org.json.JSONArray]
This is what the feed object from the get request will look like, just so you have an idea of what it is:
{
"feed": [
{
"type": "post",
"slug": "equ2ZfaX2UThtkS8DzkXdc",
"author": {
"id": "00000000-0000-0000-0000-000000000000",
"name": "Archie",
"username": "archie",
"plus": true
},
"content": "I know it's quite inactive here atm. But I'm doing tons of stuff behind the scenes - basically rewriting the entire platform from scratch. Micro will be done by the end of the summer.",
"image": null,
"createdAt": "2020-07-30T20:39:23.000Z",
"score": 5,
"vote": 0,
"replyCount": 0,
"hasParent": false
}
]
}
What could possibly be going wrong here. I am using Fuel for the request, but I don't think that is the problem
Pretty sure the correct way to get the array would be to do var feed = responseJSON.getJSONArray("feed"). You're implementation calls the JSONArray(Object o) constructor which is meant to be called only for primitive arrays (int[], double[], etc.) as they cannot be effectively typed using generics). Thus the constructor complains as you pass in an object which is not a primitive array.

Trying to call a variable from JSON

New to AngularJS so apologies if my terminology isn't correct. I am trying to call a value that is in my JSON body, however the difference is that it's also inside another body called student.
{
"id": 3,
"teacherName": "N/A",
"students": [
{
"student": "n/a"
}
],
"status": "ALIVE"
}
My JS code consists of the following:
$scope.table = function () {
SpringDataRestService.get(
{
collection: "school",
resource: $scope.teacherSelected.id
},
function (response) {
var students= [];
for (var j = 0; j < response.students.length; j++) {
var entitlement= {
student: response[j].student,
};
students.push(entitlement);
}
$log.info(JSON.stringify(entitlement))
$scope.tableOptions = new NgTableParams({}, {
dataset: students,
counts: []
});
}
);
};
There is an error in for loop. Instead of:
student: response[j].student
you need to use this:
student: response.students[j].student
Check this working demo: DEMO

Push items in objects from array when match

I have an array and object of items, I want to check each item in that array if its path has that object name, I push it in that object array.
So far this is all good, now if no match found I want to create a new item based on that array item name and push it inside it!
All my attempts ending in duplicated value, I think I need a third object/array I just can't think it anymore
To explain better:
cList = {
"rList": {
"Significant": [
{
"Path": "Significant\\Significant Charts",
"Name": "Charts"
}
]
},
};
and
SSList = {
value: [
{
"Name": "Test long name",
"Path": "/someFolder/Test long name",
},
{
"Name": "Untitled",
"Path": "/Significant/Untitled",
}
]
};
My current code
for (var cFolder in this.cList.rList) {
this.SSList.forEach((ssFile)=> {
if(ssFile.Path.indexOf(cFolder) >= 0){
this.cList.rList[cFolder].push(ssFile);
}
});
}
The first item in SSList will not be pushed since it doesn't match, I want to create a array and push it to inside rList
var folderName = ssFile.Path.split("/");
this.cList.rList[folderName[1]].push(ssFile);
One way to do it is to flip your inner and outer loops
let found = false;
this.SSList.value.forEach((ssFile) => {
for (var cFolder in this.cList.rList) {
if(ssFile.Path.indexOf(cFolder) >= 0){
found = true;
break;
}
}
if (found) {
this.cList.rList[cFolder].push(ssFile);
} else {
folderName = ssFile.Path.split("/");
if (!(folderName[1] in this.cList.rList))
this.cList.rList[folderName[1]] = [];
this.cList.rList[folderName[1]].push(ssFile);
}
found = false;
});

Resources