Skip to content

Instantly share code, notes, and snippets.

@p32929
Created April 12, 2024 00:03
Show Gist options
  • Save p32929/0a57c801666b0d76cffbf08eeb73e245 to your computer and use it in GitHub Desktop.
Save p32929/0a57c801666b0d76cffbf08eeb73e245 to your computer and use it in GitHub Desktop.
import 'dart:convert';
dynamic parseJson(String jsonString, String path) {
var json = jsonDecode(jsonString);
List<String> parts = path.split('.');
dynamic element = json;
for (var part in parts) {
if (part.contains('[') && part.contains(']')) {
var indexStart = part.indexOf('[');
var indexEnd = part.indexOf(']');
String key = part.substring(0, indexStart);
int index = int.parse(part.substring(indexStart + 1, indexEnd));
element = element[key][index];
} else {
element = element[part];
}
}
return element;
}
@p32929
Copy link
Author

p32929 commented Sep 16, 2025

JSON Parser Usage Guide

This guide demonstrates how to use the parseJson function to extract values from JSON strings using dot-notation paths.

Function Signature

dynamic parseJson(String jsonString, String path)

Sample JSON Data

For these examples, we'll use this JSON structure:

{
  "user": {
    "id": 123,
    "name": "John Doe",
    "email": "[email protected]",
    "profile": {
      "age": 28,
      "location": "New York",
      "preferences": {
        "theme": "dark",
        "notifications": true
      }
    }
  },
  "posts": [
    {
      "id": 1,
      "title": "First Post",
      "content": "Hello World!",
      "tags": ["intro", "welcome"],
      "metadata": {
        "views": 150,
        "likes": 23
      }
    },
    {
      "id": 2,
      "title": "Second Post",
      "content": "Learning Dart",
      "tags": ["programming", "dart"],
      "metadata": {
        "views": 89,
        "likes": 12
      }
    }
  ],
  "settings": {
    "isActive": true,
    "maxPosts": 10
  }
}

Usage Examples

1. Simple Object Access

String jsonString = '{"user": {"name": "John Doe", "age": 28}}';

// Get user name
var userName = parseJson(jsonString, "user.name");
print(userName); // Output: John Doe

// Get user age
var userAge = parseJson(jsonString, "user.age");
print(userAge); // Output: 28

2. Nested Object Access

// Access deeply nested properties
var theme = parseJson(jsonString, "user.profile.preferences.theme");
print(theme); // Output: dark

var location = parseJson(jsonString, "user.profile.location");
print(location); // Output: New York

3. Array Access

// Get first post title
var firstPostTitle = parseJson(jsonString, "posts[0].title");
print(firstPostTitle); // Output: First Post

// Get second post's like count
var secondPostLikes = parseJson(jsonString, "posts[1].metadata.likes");
print(secondPostLikes); // Output: 12

// Get first tag of second post
var firstTag = parseJson(jsonString, "posts[1].tags[0]");
print(firstTag); // Output: programming

4. Boolean and Numeric Values

// Get boolean value
var isActive = parseJson(jsonString, "settings.isActive");
print(isActive); // Output: true

// Get numeric value
var maxPosts = parseJson(jsonString, "settings.maxPosts");
print(maxPosts); // Output: 10

// Get user ID
var userId = parseJson(jsonString, "user.id");
print(userId); // Output: 123

5. Complete Working Example

import 'dart:convert';

dynamic parseJson(String jsonString, String path) {
  var json = jsonDecode(jsonString);
  List<String> parts = path.split('.');
  dynamic element = json;

  for (var part in parts) {
    if (part.contains('[') && part.contains(']')) {
      var indexStart = part.indexOf('[');
      var indexEnd = part.indexOf(']');
      String key = part.substring(0, indexStart);
      int index = int.parse(part.substring(indexStart + 1, indexEnd));
      element = element[key][index];
    } else {
      element = element[part];
    }
  }
  return element;
}

void main() {
  String jsonData = '''
  {
    "users": [
      {"name": "Alice", "age": 30, "city": "Boston"},
      {"name": "Bob", "age": 25, "city": "Seattle"}
    ],
    "company": {
      "name": "Tech Corp",
      "departments": ["Engineering", "Marketing", "Sales"]
    }
  }
  ''';

  // Extract various values
  print('First user name: ${parseJson(jsonData, "users[0].name")}');
  print('Second user city: ${parseJson(jsonData, "users[1].city")}');
  print('Company name: ${parseJson(jsonData, "company.name")}');
  print('First department: ${parseJson(jsonData, "company.departments[0]")}');
  print('Second user age: ${parseJson(jsonData, "users[1].age")}');
}

Supported Path Formats

Path Format Description Example
"key" Simple object property "name"
"key1.key2" Nested object property "user.name"
"array[0]" Array element "posts[0]"
"array[0].key" Object property in array "users[0].name"
"key.array[1].nested" Complex nested access "posts[1].metadata.views"

Important Notes

  • The function returns dynamic type, so you may need to cast the result
  • Array indices are zero-based (first element is [0])
  • Paths are case-sensitive
  • No error handling is included, so invalid paths will throw exceptions
  • Special characters in JSON keys (like dots or brackets) are not supported

Error Scenarios to Avoid

// These will cause runtime errors:
parseJson(jsonString, "nonexistent.key");      // Key doesn't exist
parseJson(jsonString, "posts[99].title");      // Array index out of bounds
parseJson(jsonString, "user.profile.missing"); // Null access

Consider adding try-catch blocks when using this function in production code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment