From 3afe5ea6b6e01051cab89e5aebde06f80ed92d90 Mon Sep 17 00:00:00 2001
From: Jakob Olsson <jakob.olsson@iopsys.eu>
Date: Mon, 30 Sep 2019 16:36:08 +0200
Subject: [PATCH] support more complex array manipulation

---
 api.c | 26 +++++++++++++++++++-------
 1 file changed, 19 insertions(+), 7 deletions(-)

diff --git a/api.c b/api.c
index fbc9dea..6fcd590 100644
--- a/api.c
+++ b/api.c
@@ -153,6 +153,9 @@ int set_by_string(char *fmt, struct json_object **src, char *val, enum json_type
 		*src = json_object_new_object();
 	}
 
+	printf("format = %s\n", fmt);
+	printf("set val = %s\n", val);
+
 	ptr = tmp = *src;
 
 	strcpy(buffer, fmt);
@@ -164,16 +167,18 @@ int set_by_string(char *fmt, struct json_object **src, char *val, enum json_type
 
 		/* if next key exists, parse prev key, let switch-case add/alter last key */
 		if (p) {
+			/* TODO: pretty wonky order with get idx first to overwrite braces?*/
+			idx = get_idx(prev);
 			json_object_object_get_ex(tmp, prev, &ptr);
 			/* if we need to step further and currently marked value isnt an object, we need to overwrite it */
-			if (!json_object_is_type(ptr, json_type_object)) {
+			if (!json_object_is_type(ptr, json_type_object) && !json_object_is_type(ptr, json_type_array)) {
+				printf("lets create new object hahah! key = %s\n", prev);
 				ptr = json_object_new_object();
 				json_object_object_add(tmp, prev, ptr);
 			}
 			printf("p=%s\n", p);
 
 			/* TODO: if prev contains [x], get idx of x */
-			idx = get_idx(prev);
 			printf("%s %d\n", __func__, __LINE__);
 			/* TODO: make enums for rv of get_idx */
 			if (idx != -2) {
@@ -220,8 +225,15 @@ int set_by_string(char *fmt, struct json_object **src, char *val, enum json_type
 			return -1;
 		}
 
-		json_object_object_foreach(parsed_val, key1, val1)
-			json_object_object_add(*src, key1, val1);
+		/* TODO: does this actually work? what would be the test case for this? */
+		idx = get_idx(prev);
+		if (idx == -2) {
+			json_object_object_foreach(parsed_val, key1, val1)
+				json_object_object_add(*src, key1, val1);
+		} else {
+			printf("%s %d\n", __func__, __LINE__);
+			add_array(ptr, idx, val, type, prev);
+		}
 	}
 	break;
 	case json_type_string:
@@ -350,15 +362,15 @@ int main()
 	printf("tets_arr = %s\n", json_object_get_string(obj_arr));
 
 
-	printf("%s %d obj=%s\n", __func__, __LINE__, json_object_get_string(obj));
+	printf("original obj=%s\n", json_object_get_string(obj));
 
 	ptr = get("nested", obj);
 
 	printf("%s\n", json_object_get_string(ptr));
 
-	set_by_string("test.apdfgj[0]", &obj, "1", json_type_string);
+	set_by_string("test.apdfgj[1].test", &obj, "gå och häng dig", json_type_string);
 
-	printf("%s\n", json_object_get_string(obj));
+	printf("result: %s\n", json_object_get_string(obj));
 
 	json_object_put(obj);
 	return 0;
-- 
GitLab