Created
April 12, 2024 00:03
-
-
Save p32929/0a57c801666b0d76cffbf08eeb73e245 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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
Sample JSON Data
For these examples, we'll use this JSON structure:
Usage Examples
1. Simple Object Access
2. Nested Object Access
3. Array Access
4. Boolean and Numeric Values
5. Complete Working Example
Supported Path Formats
"key"
"name"
"key1.key2"
"user.name"
"array[0]"
"posts[0]"
"array[0].key"
"users[0].name"
"key.array[1].nested"
"posts[1].metadata.views"
Important Notes
dynamic
type, so you may need to cast the result[0]
)Error Scenarios to Avoid
Consider adding try-catch blocks when using this function in production code.