Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Indexed array to TOON (Token-Oriented Object Notation) code in Nodejs/python/C/golang.
- Nodejs:
- // arrayToToon.js
- /**
- * Usage:
- * node arrayToToon.js employees '[{"id":1,"name":"John","dept":"IT"},{"id":2,"name":"Jane","dept":"HR"}]'
- * node arrayToToon.js employees '[{"id":"abc","name":"John Doe","department":"Engineering"},{"id":"cdf","name":"Jane Smith","department":"Marketing"}]'
- *
- * Output: TOON format string
- * Note: On Windows CMD, use double quotes around the JSON array:
- * node arrayToToon.js employees "[{\"id\":\"abc\",\"name\":\"John Doe\",\"department\":\"Engineering\"},{\"id\":\"cdf\",\"name\":\"Jane Smith\",\"department\":\"Marketing\"}]"
- */
- function arrayToToon(arrayName, jsonArray) {
- if (!Array.isArray(jsonArray) || jsonArray.length === 0) {
- throw new Error('Input must be a non-empty array of objects');
- }
- // Get fields from the first object (assume all objects have the same fields)
- const fields = Object.keys(jsonArray[0]);
- const count = jsonArray.length;
- // Validate all objects have the same fields
- for (const obj of jsonArray) {
- const objKeys = Object.keys(obj);
- if (objKeys.length !== fields.length || !fields.every(field => objKeys.includes(field))) {
- throw new Error('All objects must have the same fields');
- }
- }
- // Build data rows
- const rows = jsonArray.map(obj => {
- return fields.map(field => {
- let value = obj[field];
- // Escape commas in values if necessary (simple handling: wrap in quotes if contains comma or space)
- if (typeof value === 'string' && (value.includes(',') || value.includes(' '))) {
- value = `"${value.replace(/"/g, '\\"')}"`;
- }
- return value;
- }).join(',');
- });
- // Construct TOON string
- const header = `${arrayName}[${count}]{${fields.join(',')}}:`;
- const data = rows.join(' ');
- return `${header} ${data}`;
- }
- // Main
- if (process.argv.length < 4) {
- console.error('Usage: node arrayToToon.js <arrayName> \'<jsonArray>\'');
- console.error('On Windows, use double quotes: node arrayToToon.js <arrayName> "<jsonArray>"');
- console.error('Example:');
- console.error(' node arrayToToon.js employees \'[{"id":1,"name":"John","dept":"IT"},{"id":2,"name":"Jane","dept":"HR"}]\'');
- process.exit(1);
- }
- const arrayName = process.argv[2];
- let jsonString = process.argv.slice(3).join(' '); // Join remaining args in case JSON has spaces
- // Strip outer single or double quotes if present
- jsonString = jsonString.replace(/^(["'])(.*)\1$/, '$2');
- try {
- const jsonArray = JSON.parse(jsonString);
- const toonString = arrayToToon(arrayName, jsonArray);
- console.log(toonString);
- } catch (err) {
- console.error('Error:', err.message);
- process.exit(1);
- }
- Python:
- # array_to_toon.py
- import sys
- import json
- def array_to_toon(array_name, json_array):
- if not isinstance(json_array, list) or len(json_array) == 0:
- raise ValueError('Input must be a non-empty array of objects')
- # Get fields from the first object (assume all objects have the same fields)
- fields = list(json_array[0].keys())
- count = len(json_array)
- # Validate all objects have the same fields
- for obj in json_array:
- obj_keys = list(obj.keys())
- if len(obj_keys) != len(fields) or not all(field in obj_keys for field in fields):
- raise ValueError('All objects must have the same fields')
- # Build data rows
- rows = []
- for obj in json_array:
- row = []
- for field in fields:
- value = obj[field]
- # Convert to string
- value_str = str(value)
- # Escape commas and spaces if necessary (wrap in quotes if contains comma or space)
- if ',' in value_str or ' ' in value_str:
- value_str = f'"{value_str.replace('"', '\\"')}"'
- row.append(value_str)
- rows.append(','.join(row))
- # Construct TOON string
- header = f"{array_name}[{count}]{{{','.join(fields)}}}:"
- data = ' '.join(rows)
- return f"{header} {data}"
- if __name__ == "__main__":
- if len(sys.argv) < 3:
- print('Usage: python array_to_toon.py <arrayName> \'<jsonArray>\'')
- print('On Windows, use double quotes: python array_to_toon.py <arrayName> "<jsonArray>"')
- print('Example:')
- print(' python array_to_toon.py employees \'[{"id":1,"name":"John","dept":"IT"},{"id":2,"name":"Jane","dept":"HR"}]\'')
- sys.exit(1)
- array_name = sys.argv[1]
- json_string = ' '.join(sys.argv[2:]) # Join remaining args in case JSON has spaces
- # Strip outer single or double quotes if present
- if (json_string.startswith('"') and json_string.endswith('"')) or (json_string.startswith("'") and json_string.endswith("'")):
- json_string = json_string[1:-1]
- try:
- json_array = json.loads(json_string)
- toon_string = array_to_toon(array_name, json_array)
- print(toon_string)
- except ValueError as err:
- print('Error:', err)
- sys.exit(1)
- except json.JSONDecodeError as err:
- print('Error: Invalid JSON -', err)
- sys.exit(1)
- C:
- // array_to_toon.c
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <ctype.h>
- // Simple JSON parser for array of objects (assumes flat structure, no nested objects/arrays)
- // This is a basic parser for this specific use case
- typedef struct {
- char* key;
- char* value; // Stored as string
- } Pair;
- typedef struct {
- Pair* pairs;
- int count;
- } Object;
- typedef struct {
- Object* objects;
- int count;
- } Array;
- // Trim whitespace
- char* trim(char* str) {
- char* end;
- while (isspace((unsigned char)*str)) str++;
- if (*str == 0) return str;
- end = str + strlen(str) - 1;
- while (end > str && isspace((unsigned char)*end)) end--;
- end[1] = '\0';
- return str;
- }
- // Parse string value (handles quoted strings)
- char* parse_string(const char** json) {
- if (**json != '"') return NULL;
- (*json)++;
- const char* start = *json;
- while (**json && **json != '"') (*json)++;
- if (**json != '"') return NULL;
- size_t len = *json - start;
- char* str = malloc(len + 1);
- strncpy(str, start, len);
- str[len] = '\0';
- (*json)++;
- return str;
- }
- // Parse number value as string
- char* parse_number(const char** json) {
- const char* start = *json;
- while (isdigit((unsigned char)**json) || **json == '-' || **json == '.') (*json)++;
- size_t len = *json - start;
- char* str = malloc(len + 1);
- strncpy(str, start, len);
- str[len] = '\0';
- return str;
- }
- // Parse key-value pair
- int parse_pair(const char** json, Pair* pair) {
- pair->key = parse_string(json);
- if (!pair->key) return 0;
- while (isspace((unsigned char)**json)) (*json)++;
- if (**json != ':') return 0;
- (*json)++;
- while (isspace((unsigned char)**json)) (*json)++;
- if (**json == '"') {
- pair->value = parse_string(json);
- } else if (isdigit((unsigned char)**json) || **json == '-') {
- pair->value = parse_number(json);
- } else {
- return 0;
- }
- return 1;
- }
- // Parse object
- int parse_object(const char** json, Object* obj) {
- if (**json != '{') return 0;
- (*json)++;
- obj->pairs = NULL;
- obj->count = 0;
- while (1) {
- while (isspace((unsigned char)**json)) (*json)++;
- if (**json == '}') {
- (*json)++;
- return 1;
- }
- obj->pairs = realloc(obj->pairs, sizeof(Pair) * (obj->count + 1));
- if (!parse_pair(json, &obj->pairs[obj->count])) return 0;
- obj->count++;
- while (isspace((unsigned char)**json)) (*json)++;
- if (**json == ',') (*json)++;
- else if (**json == '}') {
- (*json)++;
- return 1;
- } else return 0;
- }
- }
- // Parse array
- int parse_array(const char** json, Array* arr) {
- if (**json != '[') return 0;
- (*json)++;
- arr->objects = NULL;
- arr->count = 0;
- while (1) {
- while (isspace((unsigned char)**json)) (*json)++;
- if (**json == ']') {
- (*json)++;
- return 1;
- }
- arr->objects = realloc(arr->objects, sizeof(Object) * (arr->count + 1));
- if (!parse_object(json, &arr->objects[arr->count])) return 0;
- arr->count++;
- while (isspace((unsigned char)**json)) (*json)++;
- if (**json == ',') (*json)++;
- else if (**json == ']') {
- (*json)++;
- return 1;
- } else return 0;
- }
- }
- char* array_to_toon(const char* array_name, const Array* arr) {
- if (arr->count == 0) return NULL;
- // Get fields from first object
- int num_fields = arr->objects[0].count;
- char** fields = malloc(sizeof(char*) * num_fields);
- for (int i = 0; i < num_fields; i++) {
- fields[i] = strdup(arr->objects[0].pairs[i].key);
- }
- // Validate all objects have same fields
- for (int i = 1; i < arr->count; i++) {
- if (arr->objects[i].count != num_fields) return NULL;
- for (int j = 0; j < num_fields; j++) {
- if (strcmp(arr->objects[i].pairs[j].key, fields[j]) != 0) return NULL;
- }
- }
- // Build header
- char* fields_str = malloc(1);
- fields_str[0] = '\0';
- for (int i = 0; i < num_fields; i++) {
- fields_str = realloc(fields_str, strlen(fields_str) + strlen(fields[i]) + 2);
- strcat(fields_str, fields[i]);
- if (i < num_fields - 1) strcat(fields_str, ",");
- }
- char header[1024];
- snprintf(header, sizeof(header), "%s[%d]{%s}: ", array_name, arr->count, fields_str);
- free(fields_str);
- // Build data
- char* data = malloc(1);
- data[0] = '\0';
- for (int i = 0; i < arr->count; i++) {
- for (int j = 0; j < num_fields; j++) {
- char* value = arr->objects[i].pairs[j].value;
- int needs_quotes = (strchr(value, ',') || strchr(value, ' '));
- char* esc_value = malloc(strlen(value) * 2 + 3); // For quotes and escapes
- if (needs_quotes) {
- sprintf(esc_value, "\"%s\"", value);
- } else {
- strcpy(esc_value, value);
- }
- data = realloc(data, strlen(data) + strlen(esc_value) + 2);
- strcat(data, esc_value);
- if (j < num_fields - 1) strcat(data, ",");
- free(esc_value);
- }
- if (i < arr->count - 1) strcat(data, " ");
- }
- // Combine
- char* result = malloc(strlen(header) + strlen(data) + 1);
- strcpy(result, header);
- strcat(result, data);
- // Free memory
- for (int i = 0; i < num_fields; i++) free(fields[i]);
- free(fields);
- free(data);
- return result;
- }
- int main(int argc, char* argv[]) {
- if (argc < 3) {
- fprintf(stderr, "Usage: %s <arrayName> '<jsonArray>'\n", argv[0]);
- fprintf(stderr, "Example:\n");
- fprintf(stderr, " %s employees '[{\"id\":1,\"name\":\"John\",\"dept\":\"IT\"},{\"id\":2,\"name\":\"Jane\",\"dept\":\"HR\"}]'\n", argv[0]);
- return 1;
- }
- char* array_name = argv[1];
- char* json_string = argv[2];
- // Strip outer quotes if present
- json_string = trim(json_string);
- if (json_string[0] == '"' || json_string[0] == '\'') json_string++;
- if (json_string[strlen(json_string)-1] == '"' || json_string[strlen(json_string)-1] == '\'') json_string[strlen(json_string)-1] = '\0';
- const char* ptr = json_string;
- Array arr;
- if (!parse_array(&ptr, &arr)) {
- fprintf(stderr, "Error: Invalid JSON\n");
- return 1;
- }
- char* toon = array_to_toon(array_name, &arr);
- if (!toon) {
- fprintf(stderr, "Error: Conversion failed\n");
- // Free arr memory
- for (int i = 0; i < arr.count; i++) {
- for (int j = 0; j < arr.objects[i].count; j++) {
- free(arr.objects[i].pairs[j].key);
- free(arr.objects[i].pairs[j].value);
- }
- free(arr.objects[i].pairs);
- }
- free(arr.objects);
- return 1;
- }
- printf("%s\n", toon);
- // Free memory
- free(toon);
- for (int i = 0; i < arr.count; i++) {
- for (int j = 0; j < arr.objects[i].count; j++) {
- free(arr.objects[i].pairs[j].key);
- free(arr.objects[i].pairs[j].value);
- }
- free(arr.objects[i].pairs);
- }
- free(arr.objects);
- return 0;
- }
- Golang:
- // array_to_toon.go
- package main
- import (
- "encoding/json"
- "fmt"
- "os"
- "strings"
- )
- func arrayToToon(arrayName string, jsonArray []map[string]interface{}) (string, error) {
- if len(jsonArray) == 0 {
- return "", fmt.Errorf("input must be a non-empty array of objects")
- }
- // Get fields from the first object (assume all objects have the same fields)
- fields := []string{}
- for k := range jsonArray[0] {
- fields = append(fields, k)
- }
- count := len(jsonArray)
- // Validate all objects have the same fields
- for _, obj := range jsonArray {
- objKeys := []string{}
- for k := range obj {
- objKeys = append(objKeys, k)
- }
- if len(objKeys) != len(fields) {
- return "", fmt.Errorf("all objects must have the same fields")
- }
- for _, field := range fields {
- if _, ok := obj[field]; !ok {
- return "", fmt.Errorf("all objects must have the same fields")
- }
- }
- }
- // Build data rows
- rows := []string{}
- for _, obj := range jsonArray {
- rowParts := []string{}
- for _, field := range fields {
- value := fmt.Sprintf("%v", obj[field])
- // Escape if contains comma or space
- if strings.Contains(value, ",") || strings.Contains(value, " ") {
- value = fmt.Sprintf("\"%s\"", strings.ReplaceAll(value, "\"", "\\\""))
- }
- rowParts = append(rowParts, value)
- }
- rows = append(rows, strings.Join(rowParts, ","))
- }
- // Construct TOON string
- header := fmt.Sprintf("%s[%d]{%s}:", arrayName, count, strings.Join(fields, ","))
- data := strings.Join(rows, " ")
- return fmt.Sprintf("%s %s", header, data), nil
- }
- func main() {
- if len(os.Args) < 3 {
- fmt.Printf("Usage: %s <arrayName> '<jsonArray>'\n", os.Args[0])
- fmt.Println("On Windows, use double quotes: <arrayName> \"<jsonArray>\"")
- fmt.Println("Example:")
- fmt.Printf(" %s employees '[{\"id\":1,\"name\":\"John\",\"dept\":\"IT\"},{\"id\":2,\"name\":\"Jane\",\"dept\":\"HR\"}]'\n", os.Args[0])
- os.Exit(1)
- }
- arrayName := os.Args[1]
- jsonString := strings.Join(os.Args[2:], " ")
- // Strip outer quotes if present
- jsonString = strings.TrimSpace(jsonString)
- if (strings.HasPrefix(jsonString, "\"") && strings.HasSuffix(jsonString, "\"")) || (strings.HasPrefix(jsonString, "'") && strings.HasSuffix(jsonString, "'")) {
- jsonString = jsonString[1 : len(jsonString)-1]
- }
- var jsonArray []map[string]interface{}
- err := json.Unmarshal([]byte(jsonString), &jsonArray)
- if err != nil {
- fmt.Println("Error: Invalid JSON -", err)
- os.Exit(1)
- }
- toonString, err := arrayToToon(arrayName, jsonArray)
- if err != nil {
- fmt.Println("Error:", err)
- os.Exit(1)
- }
- fmt.Println(toonString)
- }
Advertisement