CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-hjson--hjson

Hjson (Human JSON) configuration file format library for Java providing parsing and generation capabilities with human-friendly features.

Pending
Overview
Eval results
Files

json-arrays.mddocs/

JSON Array Operations

Create, modify, and iterate over JSON arrays with type-safe element access, fluent construction, and comprehensive array management capabilities.

Capabilities

Array Creation

Create JSON arrays with constructors and static factory methods.

/**
 * Creates an empty JSON array
 */
JsonArray();

/**
 * Creates a JSON array as a copy of another array
 * @param array the JSON array to copy
 */
JsonArray(JsonArray array);

/**
 * Creates an unmodifiable view of the given JSON array
 * @param array the JSON array to wrap
 * @return unmodifiable JSON array view
 */
static JsonArray unmodifiableArray(JsonArray array);

Usage Examples:

import org.hjson.JsonArray;
import org.hjson.JsonValue;

// Create empty array
JsonArray emptyArray = new JsonArray();

// Create array with initial data
JsonArray numbers = new JsonArray()
    .add(1)
    .add(2)
    .add(3)
    .add(4)
    .add(5);

// Copy constructor
JsonArray numbersCopy = new JsonArray(numbers);

// Unmodifiable view
JsonArray readOnlyNumbers = JsonArray.unmodifiableArray(numbers);

Adding Elements (Fluent Interface)

Add new elements to JSON arrays with type-specific convenience methods.

/**
 * Appends the specified JSON value to the end of this array
 * @param value the JSON value to be appended to this array
 * @return the JSON array itself, to enable method chaining
 */
JsonArray add(JsonValue value);

/**
 * Appends the specified string value to the end of this array
 * @param value the string value to be appended to this array
 * @return the JSON array itself, to enable method chaining
 */
JsonArray add(String value);

/**
 * Appends the specified int value to the end of this array
 * @param value the int value to be appended to this array
 * @return the JSON array itself, to enable method chaining
 */
JsonArray add(int value);

/**
 * Appends the specified long value to the end of this array
 * @param value the long value to be appended to this array
 * @return the JSON array itself, to enable method chaining
 */
JsonArray add(long value);

/**
 * Appends the specified float value to the end of this array
 * @param value the float value to be appended to this array
 * @return the JSON array itself, to enable method chaining
 */
JsonArray add(float value);

/**
 * Appends the specified double value to the end of this array
 * @param value the double value to be appended to this array
 * @return the JSON array itself, to enable method chaining
 */
JsonArray add(double value);

/**
 * Appends the specified boolean value to the end of this array
 * @param value the boolean value to be appended to this array
 * @return the JSON array itself, to enable method chaining
 */
JsonArray add(boolean value);

Usage Examples:

import org.hjson.JsonArray;
import org.hjson.JsonObject;
import org.hjson.JsonValue;

// Build arrays with fluent interface
JsonArray mixedArray = new JsonArray()
    .add("Hello")
    .add(42)
    .add(true)
    .add(3.14)
    .add(JsonValue.NULL);

// Create array of objects
JsonArray users = new JsonArray();
for (int i = 1; i <= 3; i++) {
    JsonObject user = new JsonObject()
        .add("id", i)
        .add("name", "User " + i)
        .add("active", i % 2 == 1);
    users.add(user);
}

// Array of arrays (nested structure)
JsonArray matrix = new JsonArray()
    .add(new JsonArray().add(1).add(2).add(3))
    .add(new JsonArray().add(4).add(5).add(6))
    .add(new JsonArray().add(7).add(8).add(9));

Setting/Replacing Elements

Replace existing elements at specific indices with set methods.

/**
 * Replaces the element at the specified position with the specified JSON value
 * @param index the index of the element to replace
 * @param value the JSON value to be stored at the specified position
 * @return the JSON array itself, to enable method chaining
 * @throws IndexOutOfBoundsException if the index is out of range
 */
JsonArray set(int index, JsonValue value);

/**
 * Replaces the element at the specified position with the specified string value
 * @param index the index of the element to replace
 * @param value the string value to be stored at the specified position
 * @return the JSON array itself, to enable method chaining
 * @throws IndexOutOfBoundsException if the index is out of range
 */
JsonArray set(int index, String value);

/**
 * Replaces the element at the specified position with the specified int value
 * @param index the index of the element to replace
 * @param value the int value to be stored at the specified position
 * @return the JSON array itself, to enable method chaining
 * @throws IndexOutOfBoundsException if the index is out of range
 */
JsonArray set(int index, int value);

/**
 * Replaces the element at the specified position with the specified long value
 * @param index the index of the element to replace
 * @param value the long value to be stored at the specified position
 * @return the JSON array itself, to enable method chaining
 * @throws IndexOutOfBoundsException if the index is out of range
 */
JsonArray set(int index, long value);

/**
 * Replaces the element at the specified position with the specified float value
 * @param index the index of the element to replace
 * @param value the float value to be stored at the specified position
 * @return the JSON array itself, to enable method chaining
 * @throws IndexOutOfBoundsException if the index is out of range
 */
JsonArray set(int index, float value);

/**
 * Replaces the element at the specified position with the specified double value
 * @param index the index of the element to replace
 * @param value the double value to be stored at the specified position
 * @return the JSON array itself, to enable method chaining
 * @throws IndexOutOfBoundsException if the index is out of range
 */
JsonArray set(int index, double value);

/**
 * Replaces the element at the specified position with the specified boolean value
 * @param index the index of the element to replace
 * @param value the boolean value to be stored at the specified position
 * @return the JSON array itself, to enable method chaining
 * @throws IndexOutOfBoundsException if the index is out of range
 */
JsonArray set(int index, boolean value);

Usage Examples:

import org.hjson.JsonArray;

// Create array with initial values
JsonArray scores = new JsonArray()
    .add(85)
    .add(92)
    .add(76)
    .add(88);

// Update specific elements
scores.set(0, 87)    // Update first score
      .set(2, 78);   // Update third score

// Conditional updates
if (someCondition) {
    scores.set(scores.size() - 1, 95); // Update last element
}

// Replace with different types (be careful with type consistency)
JsonArray mixed = new JsonArray()
    .add("initial")
    .add(100);

mixed.set(0, "updated")  // String to string
     .set(1, 200);       // Number to number

Accessing Elements

Retrieve array elements by index with bounds checking.

/**
 * Returns the value of the element at the specified position in this array
 * @param index the index of the array element to return
 * @return the value of the element at the specified position
 * @throws IndexOutOfBoundsException if the index is out of range
 */
JsonValue get(int index);

Usage Examples:

import org.hjson.JsonArray;
import org.hjson.JsonValue;
import org.hjson.JsonObject;

JsonArray data = JsonValue.readHjson("""
    [
        { name: "Alice", score: 95 },
        { name: "Bob", score: 87 },
        { name: "Charlie", score: 91 }
    ]
    """).asArray();

// Safe element access with bounds checking
for (int i = 0; i < data.size(); i++) {
    JsonValue element = data.get(i);
    if (element.isObject()) {
        JsonObject person = element.asObject();
        String name = person.getString("name", "Unknown");
        int score = person.getInt("score", 0);
        System.out.println(name + ": " + score);
    }
}

// Access specific elements
if (data.size() > 0) {
    JsonValue first = data.get(0);
    JsonValue last = data.get(data.size() - 1);
    
    // Process first and last elements
    System.out.println("First: " + first);
    System.out.println("Last: " + last);
}

// Handle potential IndexOutOfBoundsException
try {
    JsonValue element = data.get(10); // May throw exception
} catch (IndexOutOfBoundsException e) {
    System.err.println("Index out of bounds: " + e.getMessage());
}

Array Management

Remove elements and query array structure.

/**
 * Removes the element at the specified position from this array
 * Shifts any subsequent elements to the left (subtracts one from their indices)
 * @param index the index of the element to be removed
 * @return the JSON array itself, to enable method chaining
 * @throws IndexOutOfBoundsException if the index is out of range
 */
JsonArray remove(int index);

/**
 * Returns the number of elements in this array
 * @return the number of elements in this array
 */
int size();

/**
 * Returns true if this array contains no elements
 * @return true if this array is empty
 */
boolean isEmpty();

/**
 * Returns an unmodifiable List view of the values in this array
 * Changes to the original array are reflected in the returned list
 * @return unmodifiable list view of array elements
 */
List<JsonValue> values();

Usage Examples:

import org.hjson.JsonArray;
import java.util.List;

JsonArray items = new JsonArray()
    .add("apple")
    .add("banana")
    .add("cherry")
    .add("date");

// Query array structure
System.out.println("Size: " + items.size()); // Output: Size: 4
System.out.println("Empty: " + items.isEmpty()); // Output: Empty: false

// Remove elements (be careful with indices shifting)
items.remove(1); // Removes "banana", "cherry" shifts to index 1
System.out.println("After removal: " + items.size()); // Output: After removal: 3

// Remove from end to avoid index shifting issues
while (!items.isEmpty()) {
    items.remove(items.size() - 1); // Always remove last element
}
System.out.println("After clearing: " + items.isEmpty()); // Output: After clearing: true

// Get list view for read-only operations
JsonArray numbers = new JsonArray().add(1).add(2).add(3);
List<JsonValue> numberList = numbers.values();
System.out.println("List size: " + numberList.size()); // Output: List size: 3

// Use list for enhanced operations (read-only)
for (JsonValue value : numberList) {
    if (value.isNumber()) {
        System.out.println("Number: " + value.asInt());
    }
}

Iteration

Iterate over array elements with enhanced for-loop support.

/**
 * Returns an iterator over the elements in this array in proper sequence
 * @return iterator over JsonValue elements
 */
Iterator<JsonValue> iterator();

Usage Examples:

import org.hjson.JsonArray;
import org.hjson.JsonValue;
import java.util.Iterator;

JsonArray mixed = new JsonArray()
    .add("text")
    .add(42)
    .add(true)
    .add(3.14)
    .add(JsonValue.NULL);

// Enhanced for-loop iteration
for (JsonValue element : mixed) {
    if (element.isString()) {
        System.out.println("String: " + element.asString());
    } else if (element.isNumber()) {
        System.out.println("Number: " + element.asDouble());
    } else if (element.isBoolean()) {
        System.out.println("Boolean: " + element.asBoolean());
    } else if (element.isNull()) {
        System.out.println("Null value found");
    }
}

// Iterator-based iteration with index tracking
Iterator<JsonValue> iterator = mixed.iterator();
int index = 0;
while (iterator.hasNext()) {
    JsonValue element = iterator.next();
    System.out.println("Element " + index + ": " + element + 
                      " (type: " + element.getType() + ")");
    index++;
}

// Process array of objects
JsonArray users = new JsonArray()
    .add(new JsonObject().add("name", "Alice").add("age", 25))
    .add(new JsonObject().add("name", "Bob").add("age", 30));

for (JsonValue userValue : users) {
    if (userValue.isObject()) {
        JsonObject user = userValue.asObject();
        String name = user.getString("name", "Unknown");
        int age = user.getInt("age", 0);
        System.out.println(name + " is " + age + " years old");
    }
}

Type Checking and Conversion

JsonArray inherits type checking and conversion methods from JsonValue:

// Type checking (always returns true for JsonArray)
boolean isArray();
JsonType getType(); // Returns JsonType.ARRAY

// Safe conversion (returns this)
JsonArray asArray();

// Array equality and hashing
boolean equals(Object obj);
int hashCode();

Common Patterns and Use Cases

Building Arrays from Collections

import java.util.Arrays;
import java.util.List;

// From Java collections
List<String> javaList = Arrays.asList("a", "b", "c");
JsonArray jsonArray = new JsonArray();
for (String item : javaList) {
    jsonArray.add(item);
}

// From arrays
int[] numbers = {1, 2, 3, 4, 5};
JsonArray jsonNumbers = new JsonArray();
for (int num : numbers) {
    jsonNumbers.add(num);
}

Array Filtering and Transformation

// Filter array elements
JsonArray source = new JsonArray().add(1).add(2).add(3).add(4).add(5);
JsonArray filtered = new JsonArray();

for (JsonValue value : source) {
    if (value.isNumber() && value.asInt() % 2 == 0) {
        filtered.add(value);
    }
}

// Transform array elements
JsonArray strings = new JsonArray().add("apple").add("banana").add("cherry");
JsonArray upperCase = new JsonArray();

for (JsonValue value : strings) {
    if (value.isString()) {
        upperCase.add(value.asString().toUpperCase());
    }
}

Nested Array Operations

// Create nested arrays
JsonArray matrix = new JsonArray();
for (int row = 0; row < 3; row++) {
    JsonArray rowArray = new JsonArray();
    for (int col = 0; col < 3; col++) {
        rowArray.add(row * 3 + col + 1);
    }
    matrix.add(rowArray);
}

// Access nested elements
for (int i = 0; i < matrix.size(); i++) {
    JsonValue rowValue = matrix.get(i);
    if (rowValue.isArray()) {
        JsonArray row = rowValue.asArray();
        for (int j = 0; j < row.size(); j++) {
            System.out.print(row.get(j).asInt() + " ");
        }
        System.out.println();
    }
}

Thread Safety and Performance

  • Thread Safety: JsonArray is not thread-safe and requires external synchronization for concurrent access
  • Mutability: JsonArray instances are mutable - methods like add(), set(), and remove() modify the array
  • Performance: Element access is O(1), but removal from the middle causes O(n) shifting
  • Memory: Arrays grow dynamically as elements are added
  • Defensive Copying: Use the copy constructor or unmodifiableArray() for safe sharing

Best Practices

  1. Fluent Interface: Chain method calls for readable array construction
  2. Bounds Checking: Always check size() before accessing elements by index
  3. Type Consistency: Try to maintain consistent element types within arrays when possible
  4. Index Management: When removing multiple elements, remove from the end to avoid index shifting
  5. Null Handling: Use JsonValue.NULL for explicit null values rather than Java null
  6. Iteration: Prefer enhanced for-loops over manual index iteration when possible
  7. Unmodifiable Views: Use unmodifiableArray() when passing arrays to untrusted code
  8. Performance: For frequent modifications, consider building the array in one pass rather than multiple add/remove operations

Install with Tessl CLI

npx tessl i tessl/maven-org-hjson--hjson

docs

configuration.md

index.md

json-arrays.md

json-objects.md

parsing.md

serialization.md

types-exceptions.md

tile.json