applyJsonTransform function

dynamic applyJsonTransform(
  1. dynamic value,
  2. String? varName
)

Apply JSON transform to parse JSON strings and extract JavaScript variables

Parses JSON data or extracts JSON values from JavaScript variable assignments. Supports wildcard patterns for matching multiple variables.

Parameters

  • value - The input value (typically a string containing JSON or JavaScript)
  • varName - Optional variable name or pattern to extract from JavaScript

Variable Extraction

When varName is provided, the transform looks for JavaScript variable assignments and extracts the JSON value:

  • Exact match: json:config matches var config = {...};
  • Wildcard: json:config_* matches config_api, config_key, etc.
  • Patterns: Supports var, let, const, and property assignments

Supported Value Types

  • Objects: {...}
  • Arrays: [...]
  • Numbers: integers, decimals, scientific notation
  • Strings: single or double quoted
  • Booleans: true, false
  • Null: null

Returns

  • Parsed JSON value (object, array, primitive, boolean, or null)
  • null if parsing fails or variable not found

Examples

// Plain JSON
applyJsonTransform('{"x": 1}', null);  // {'x': 1}

// Variable extraction
applyJsonTransform('var data = [1,2,3];', 'data');  // [1, 2, 3]

// Wildcard pattern
applyJsonTransform('var cfg_a = 1; var cfg_b = 2;', 'cfg_*');
// Extracts first match

// Null handling
applyJsonTransform(null, 'var');  // null

Implementation

dynamic applyJsonTransform(dynamic value, String? varName) {
  if (value == null) return null;

  var text = value.toString().trim();

  // If varName is provided, extract the JSON from JavaScript variable assignment
  if (varName != null && varName.isNotEmpty) {
    // Convert wildcard pattern to regex
    // Escape special regex chars except * which becomes .*
    final escapedName = RegExp.escape(varName).replaceAll(r'\*', '.*');

    // Match patterns like: var config = {...}; or window.__DATA__ = {...};
    // Note: JavaScript variables may or may not end with semicolon
    final patterns = [
      // Objects - match with or without semicolon
      RegExp('$escapedName\\s*=\\s*({[\\s\\S]*?})\\s*(?:;|\$)',
          multiLine: false),
      // Arrays - match with or without semicolon
      RegExp('$escapedName\\s*=\\s*(\\[[\\s\\S]*?\\])\\s*(?:;|\$)',
          multiLine: false),
      // Numbers (including decimals, negative, scientific notation)
      RegExp(
          '$escapedName\\s*=\\s*(-?\\d+\\.?\\d*(?:[eE][+-]?\\d+)?)\\s*(?:;|\$)',
          multiLine: false),
      // Strings (single or double quotes)
      RegExp('$escapedName\\s*=\\s*(["\'][\\s\\S]*?["\'])\\s*(?:;|\$)',
          multiLine: false),
      // Booleans
      RegExp('$escapedName\\s*=\\s*(true|false)\\s*(?:;|\$)', multiLine: false),
      // Null
      RegExp('$escapedName\\s*=\\s*(null)\\s*(?:;|\$)', multiLine: false),
    ];

    bool found = false;

    for (var pattern in patterns) {
      final match = pattern.firstMatch(text);
      if (match != null && match.groupCount >= 1) {
        text = match.group(1)!;
        found = true;
        break;
      }
    }

    if (!found) {
      return null;
    }
  }

  return tryParseJson(text, discard: true);
}