lihkgcode

Indexed array to TOON (Token-Oriented Object Notation) code in Nodejs/python/C/golang.

Nov 8th, 2025
59
0
Never
5
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.98 KB | None | 0 0
  1. Indexed array to TOON (Token-Oriented Object Notation) code in Nodejs/python/C/golang.
  2.  
  3. Nodejs:
  4.  
  5. // arrayToToon.js
  6. /**
  7. * Usage:
  8. * node arrayToToon.js employees '[{"id":1,"name":"John","dept":"IT"},{"id":2,"name":"Jane","dept":"HR"}]'
  9. * node arrayToToon.js employees '[{"id":"abc","name":"John Doe","department":"Engineering"},{"id":"cdf","name":"Jane Smith","department":"Marketing"}]'
  10. *
  11. * Output: TOON format string
  12. * Note: On Windows CMD, use double quotes around the JSON array:
  13. * node arrayToToon.js employees "[{\"id\":\"abc\",\"name\":\"John Doe\",\"department\":\"Engineering\"},{\"id\":\"cdf\",\"name\":\"Jane Smith\",\"department\":\"Marketing\"}]"
  14. */
  15.  
  16. function arrayToToon(arrayName, jsonArray) {
  17. if (!Array.isArray(jsonArray) || jsonArray.length === 0) {
  18. throw new Error('Input must be a non-empty array of objects');
  19. }
  20.  
  21. // Get fields from the first object (assume all objects have the same fields)
  22. const fields = Object.keys(jsonArray[0]);
  23. const count = jsonArray.length;
  24.  
  25. // Validate all objects have the same fields
  26. for (const obj of jsonArray) {
  27. const objKeys = Object.keys(obj);
  28. if (objKeys.length !== fields.length || !fields.every(field => objKeys.includes(field))) {
  29. throw new Error('All objects must have the same fields');
  30. }
  31. }
  32.  
  33. // Build data rows
  34. const rows = jsonArray.map(obj => {
  35. return fields.map(field => {
  36. let value = obj[field];
  37. // Escape commas in values if necessary (simple handling: wrap in quotes if contains comma or space)
  38. if (typeof value === 'string' && (value.includes(',') || value.includes(' '))) {
  39. value = `"${value.replace(/"/g, '\\"')}"`;
  40. }
  41. return value;
  42. }).join(',');
  43. });
  44.  
  45. // Construct TOON string
  46. const header = `${arrayName}[${count}]{${fields.join(',')}}:`;
  47. const data = rows.join(' ');
  48.  
  49. return `${header} ${data}`;
  50. }
  51.  
  52. // Main
  53. if (process.argv.length < 4) {
  54. console.error('Usage: node arrayToToon.js <arrayName> \'<jsonArray>\'');
  55. console.error('On Windows, use double quotes: node arrayToToon.js <arrayName> "<jsonArray>"');
  56. console.error('Example:');
  57. console.error(' node arrayToToon.js employees \'[{"id":1,"name":"John","dept":"IT"},{"id":2,"name":"Jane","dept":"HR"}]\'');
  58. process.exit(1);
  59. }
  60.  
  61. const arrayName = process.argv[2];
  62. let jsonString = process.argv.slice(3).join(' '); // Join remaining args in case JSON has spaces
  63.  
  64. // Strip outer single or double quotes if present
  65. jsonString = jsonString.replace(/^(["'])(.*)\1$/, '$2');
  66.  
  67. try {
  68. const jsonArray = JSON.parse(jsonString);
  69. const toonString = arrayToToon(arrayName, jsonArray);
  70. console.log(toonString);
  71. } catch (err) {
  72. console.error('Error:', err.message);
  73. process.exit(1);
  74. }
  75.  
  76. Python:
  77.  
  78. # array_to_toon.py
  79. import sys
  80. import json
  81.  
  82. def array_to_toon(array_name, json_array):
  83. if not isinstance(json_array, list) or len(json_array) == 0:
  84. raise ValueError('Input must be a non-empty array of objects')
  85.  
  86. # Get fields from the first object (assume all objects have the same fields)
  87. fields = list(json_array[0].keys())
  88. count = len(json_array)
  89.  
  90. # Validate all objects have the same fields
  91. for obj in json_array:
  92. obj_keys = list(obj.keys())
  93. if len(obj_keys) != len(fields) or not all(field in obj_keys for field in fields):
  94. raise ValueError('All objects must have the same fields')
  95.  
  96. # Build data rows
  97. rows = []
  98. for obj in json_array:
  99. row = []
  100. for field in fields:
  101. value = obj[field]
  102. # Convert to string
  103. value_str = str(value)
  104. # Escape commas and spaces if necessary (wrap in quotes if contains comma or space)
  105. if ',' in value_str or ' ' in value_str:
  106. value_str = f'"{value_str.replace('"', '\\"')}"'
  107. row.append(value_str)
  108. rows.append(','.join(row))
  109.  
  110. # Construct TOON string
  111. header = f"{array_name}[{count}]{{{','.join(fields)}}}:"
  112. data = ' '.join(rows)
  113.  
  114. return f"{header} {data}"
  115.  
  116. if __name__ == "__main__":
  117. if len(sys.argv) < 3:
  118. print('Usage: python array_to_toon.py <arrayName> \'<jsonArray>\'')
  119. print('On Windows, use double quotes: python array_to_toon.py <arrayName> "<jsonArray>"')
  120. print('Example:')
  121. print(' python array_to_toon.py employees \'[{"id":1,"name":"John","dept":"IT"},{"id":2,"name":"Jane","dept":"HR"}]\'')
  122. sys.exit(1)
  123.  
  124. array_name = sys.argv[1]
  125. json_string = ' '.join(sys.argv[2:]) # Join remaining args in case JSON has spaces
  126.  
  127. # Strip outer single or double quotes if present
  128. if (json_string.startswith('"') and json_string.endswith('"')) or (json_string.startswith("'") and json_string.endswith("'")):
  129. json_string = json_string[1:-1]
  130.  
  131. try:
  132. json_array = json.loads(json_string)
  133. toon_string = array_to_toon(array_name, json_array)
  134. print(toon_string)
  135. except ValueError as err:
  136. print('Error:', err)
  137. sys.exit(1)
  138. except json.JSONDecodeError as err:
  139. print('Error: Invalid JSON -', err)
  140. sys.exit(1)
  141.  
  142. C:
  143.  
  144. // array_to_toon.c
  145. #include <stdio.h>
  146. #include <stdlib.h>
  147. #include <string.h>
  148. #include <ctype.h>
  149.  
  150. // Simple JSON parser for array of objects (assumes flat structure, no nested objects/arrays)
  151. // This is a basic parser for this specific use case
  152.  
  153. typedef struct {
  154. char* key;
  155. char* value; // Stored as string
  156. } Pair;
  157.  
  158. typedef struct {
  159. Pair* pairs;
  160. int count;
  161. } Object;
  162.  
  163. typedef struct {
  164. Object* objects;
  165. int count;
  166. } Array;
  167.  
  168. // Trim whitespace
  169. char* trim(char* str) {
  170. char* end;
  171. while (isspace((unsigned char)*str)) str++;
  172. if (*str == 0) return str;
  173. end = str + strlen(str) - 1;
  174. while (end > str && isspace((unsigned char)*end)) end--;
  175. end[1] = '\0';
  176. return str;
  177. }
  178.  
  179. // Parse string value (handles quoted strings)
  180. char* parse_string(const char** json) {
  181. if (**json != '"') return NULL;
  182. (*json)++;
  183. const char* start = *json;
  184. while (**json && **json != '"') (*json)++;
  185. if (**json != '"') return NULL;
  186. size_t len = *json - start;
  187. char* str = malloc(len + 1);
  188. strncpy(str, start, len);
  189. str[len] = '\0';
  190. (*json)++;
  191. return str;
  192. }
  193.  
  194. // Parse number value as string
  195. char* parse_number(const char** json) {
  196. const char* start = *json;
  197. while (isdigit((unsigned char)**json) || **json == '-' || **json == '.') (*json)++;
  198. size_t len = *json - start;
  199. char* str = malloc(len + 1);
  200. strncpy(str, start, len);
  201. str[len] = '\0';
  202. return str;
  203. }
  204.  
  205. // Parse key-value pair
  206. int parse_pair(const char** json, Pair* pair) {
  207. pair->key = parse_string(json);
  208. if (!pair->key) return 0;
  209. while (isspace((unsigned char)**json)) (*json)++;
  210. if (**json != ':') return 0;
  211. (*json)++;
  212. while (isspace((unsigned char)**json)) (*json)++;
  213. if (**json == '"') {
  214. pair->value = parse_string(json);
  215. } else if (isdigit((unsigned char)**json) || **json == '-') {
  216. pair->value = parse_number(json);
  217. } else {
  218. return 0;
  219. }
  220. return 1;
  221. }
  222.  
  223. // Parse object
  224. int parse_object(const char** json, Object* obj) {
  225. if (**json != '{') return 0;
  226. (*json)++;
  227. obj->pairs = NULL;
  228. obj->count = 0;
  229. while (1) {
  230. while (isspace((unsigned char)**json)) (*json)++;
  231. if (**json == '}') {
  232. (*json)++;
  233. return 1;
  234. }
  235. obj->pairs = realloc(obj->pairs, sizeof(Pair) * (obj->count + 1));
  236. if (!parse_pair(json, &obj->pairs[obj->count])) return 0;
  237. obj->count++;
  238. while (isspace((unsigned char)**json)) (*json)++;
  239. if (**json == ',') (*json)++;
  240. else if (**json == '}') {
  241. (*json)++;
  242. return 1;
  243. } else return 0;
  244. }
  245. }
  246.  
  247. // Parse array
  248. int parse_array(const char** json, Array* arr) {
  249. if (**json != '[') return 0;
  250. (*json)++;
  251. arr->objects = NULL;
  252. arr->count = 0;
  253. while (1) {
  254. while (isspace((unsigned char)**json)) (*json)++;
  255. if (**json == ']') {
  256. (*json)++;
  257. return 1;
  258. }
  259. arr->objects = realloc(arr->objects, sizeof(Object) * (arr->count + 1));
  260. if (!parse_object(json, &arr->objects[arr->count])) return 0;
  261. arr->count++;
  262. while (isspace((unsigned char)**json)) (*json)++;
  263. if (**json == ',') (*json)++;
  264. else if (**json == ']') {
  265. (*json)++;
  266. return 1;
  267. } else return 0;
  268. }
  269. }
  270.  
  271. char* array_to_toon(const char* array_name, const Array* arr) {
  272. if (arr->count == 0) return NULL;
  273.  
  274. // Get fields from first object
  275. int num_fields = arr->objects[0].count;
  276. char** fields = malloc(sizeof(char*) * num_fields);
  277. for (int i = 0; i < num_fields; i++) {
  278. fields[i] = strdup(arr->objects[0].pairs[i].key);
  279. }
  280.  
  281. // Validate all objects have same fields
  282. for (int i = 1; i < arr->count; i++) {
  283. if (arr->objects[i].count != num_fields) return NULL;
  284. for (int j = 0; j < num_fields; j++) {
  285. if (strcmp(arr->objects[i].pairs[j].key, fields[j]) != 0) return NULL;
  286. }
  287. }
  288.  
  289. // Build header
  290. char* fields_str = malloc(1);
  291. fields_str[0] = '\0';
  292. for (int i = 0; i < num_fields; i++) {
  293. fields_str = realloc(fields_str, strlen(fields_str) + strlen(fields[i]) + 2);
  294. strcat(fields_str, fields[i]);
  295. if (i < num_fields - 1) strcat(fields_str, ",");
  296. }
  297. char header[1024];
  298. snprintf(header, sizeof(header), "%s[%d]{%s}: ", array_name, arr->count, fields_str);
  299. free(fields_str);
  300.  
  301. // Build data
  302. char* data = malloc(1);
  303. data[0] = '\0';
  304. for (int i = 0; i < arr->count; i++) {
  305. for (int j = 0; j < num_fields; j++) {
  306. char* value = arr->objects[i].pairs[j].value;
  307. int needs_quotes = (strchr(value, ',') || strchr(value, ' '));
  308. char* esc_value = malloc(strlen(value) * 2 + 3); // For quotes and escapes
  309. if (needs_quotes) {
  310. sprintf(esc_value, "\"%s\"", value);
  311. } else {
  312. strcpy(esc_value, value);
  313. }
  314. data = realloc(data, strlen(data) + strlen(esc_value) + 2);
  315. strcat(data, esc_value);
  316. if (j < num_fields - 1) strcat(data, ",");
  317. free(esc_value);
  318. }
  319. if (i < arr->count - 1) strcat(data, " ");
  320. }
  321.  
  322. // Combine
  323. char* result = malloc(strlen(header) + strlen(data) + 1);
  324. strcpy(result, header);
  325. strcat(result, data);
  326.  
  327. // Free memory
  328. for (int i = 0; i < num_fields; i++) free(fields[i]);
  329. free(fields);
  330. free(data);
  331.  
  332. return result;
  333. }
  334.  
  335. int main(int argc, char* argv[]) {
  336. if (argc < 3) {
  337. fprintf(stderr, "Usage: %s <arrayName> '<jsonArray>'\n", argv[0]);
  338. fprintf(stderr, "Example:\n");
  339. fprintf(stderr, " %s employees '[{\"id\":1,\"name\":\"John\",\"dept\":\"IT\"},{\"id\":2,\"name\":\"Jane\",\"dept\":\"HR\"}]'\n", argv[0]);
  340. return 1;
  341. }
  342.  
  343. char* array_name = argv[1];
  344. char* json_string = argv[2];
  345.  
  346. // Strip outer quotes if present
  347. json_string = trim(json_string);
  348. if (json_string[0] == '"' || json_string[0] == '\'') json_string++;
  349. if (json_string[strlen(json_string)-1] == '"' || json_string[strlen(json_string)-1] == '\'') json_string[strlen(json_string)-1] = '\0';
  350.  
  351. const char* ptr = json_string;
  352. Array arr;
  353. if (!parse_array(&ptr, &arr)) {
  354. fprintf(stderr, "Error: Invalid JSON\n");
  355. return 1;
  356. }
  357.  
  358. char* toon = array_to_toon(array_name, &arr);
  359. if (!toon) {
  360. fprintf(stderr, "Error: Conversion failed\n");
  361. // Free arr memory
  362. for (int i = 0; i < arr.count; i++) {
  363. for (int j = 0; j < arr.objects[i].count; j++) {
  364. free(arr.objects[i].pairs[j].key);
  365. free(arr.objects[i].pairs[j].value);
  366. }
  367. free(arr.objects[i].pairs);
  368. }
  369. free(arr.objects);
  370. return 1;
  371. }
  372.  
  373. printf("%s\n", toon);
  374.  
  375. // Free memory
  376. free(toon);
  377. for (int i = 0; i < arr.count; i++) {
  378. for (int j = 0; j < arr.objects[i].count; j++) {
  379. free(arr.objects[i].pairs[j].key);
  380. free(arr.objects[i].pairs[j].value);
  381. }
  382. free(arr.objects[i].pairs);
  383. }
  384. free(arr.objects);
  385.  
  386. return 0;
  387. }
  388.  
  389. Golang:
  390.  
  391. // array_to_toon.go
  392. package main
  393.  
  394. import (
  395. "encoding/json"
  396. "fmt"
  397. "os"
  398. "strings"
  399. )
  400.  
  401. func arrayToToon(arrayName string, jsonArray []map[string]interface{}) (string, error) {
  402. if len(jsonArray) == 0 {
  403. return "", fmt.Errorf("input must be a non-empty array of objects")
  404. }
  405.  
  406. // Get fields from the first object (assume all objects have the same fields)
  407. fields := []string{}
  408. for k := range jsonArray[0] {
  409. fields = append(fields, k)
  410. }
  411. count := len(jsonArray)
  412.  
  413. // Validate all objects have the same fields
  414. for _, obj := range jsonArray {
  415. objKeys := []string{}
  416. for k := range obj {
  417. objKeys = append(objKeys, k)
  418. }
  419. if len(objKeys) != len(fields) {
  420. return "", fmt.Errorf("all objects must have the same fields")
  421. }
  422. for _, field := range fields {
  423. if _, ok := obj[field]; !ok {
  424. return "", fmt.Errorf("all objects must have the same fields")
  425. }
  426. }
  427. }
  428.  
  429. // Build data rows
  430. rows := []string{}
  431. for _, obj := range jsonArray {
  432. rowParts := []string{}
  433. for _, field := range fields {
  434. value := fmt.Sprintf("%v", obj[field])
  435. // Escape if contains comma or space
  436. if strings.Contains(value, ",") || strings.Contains(value, " ") {
  437. value = fmt.Sprintf("\"%s\"", strings.ReplaceAll(value, "\"", "\\\""))
  438. }
  439. rowParts = append(rowParts, value)
  440. }
  441. rows = append(rows, strings.Join(rowParts, ","))
  442. }
  443.  
  444. // Construct TOON string
  445. header := fmt.Sprintf("%s[%d]{%s}:", arrayName, count, strings.Join(fields, ","))
  446. data := strings.Join(rows, " ")
  447.  
  448. return fmt.Sprintf("%s %s", header, data), nil
  449. }
  450.  
  451. func main() {
  452. if len(os.Args) < 3 {
  453. fmt.Printf("Usage: %s <arrayName> '<jsonArray>'\n", os.Args[0])
  454. fmt.Println("On Windows, use double quotes: <arrayName> \"<jsonArray>\"")
  455. fmt.Println("Example:")
  456. fmt.Printf(" %s employees '[{\"id\":1,\"name\":\"John\",\"dept\":\"IT\"},{\"id\":2,\"name\":\"Jane\",\"dept\":\"HR\"}]'\n", os.Args[0])
  457. os.Exit(1)
  458. }
  459.  
  460. arrayName := os.Args[1]
  461. jsonString := strings.Join(os.Args[2:], " ")
  462.  
  463. // Strip outer quotes if present
  464. jsonString = strings.TrimSpace(jsonString)
  465. if (strings.HasPrefix(jsonString, "\"") && strings.HasSuffix(jsonString, "\"")) || (strings.HasPrefix(jsonString, "'") && strings.HasSuffix(jsonString, "'")) {
  466. jsonString = jsonString[1 : len(jsonString)-1]
  467. }
  468.  
  469. var jsonArray []map[string]interface{}
  470. err := json.Unmarshal([]byte(jsonString), &jsonArray)
  471. if err != nil {
  472. fmt.Println("Error: Invalid JSON -", err)
  473. os.Exit(1)
  474. }
  475.  
  476. toonString, err := arrayToToon(arrayName, jsonArray)
  477. if err != nil {
  478. fmt.Println("Error:", err)
  479. os.Exit(1)
  480. }
  481.  
  482. fmt.Println(toonString)
  483. }
Advertisement
Comments
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
Add Comment
Please, Sign In to add comment