Created
August 2, 2025 15:49
-
-
Save eIektro/4ce875db62a314eed20c21348086bced to your computer and use it in GitHub Desktop.
this is performance enhanced simple json parser using memory span
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
| public void ParseJson(ReadOnlySpan<char> jsonData) | |
| { | |
| // Find the start of the value for a specific key | |
| ReadOnlySpan<char> key = "name"; | |
| int keyStart = jsonData.IndexOf(key); | |
| if (keyStart == -1) | |
| { | |
| Console.WriteLine("Key not found"); | |
| return; | |
| } | |
| // Move past the key and find the colon | |
| int valueStart = jsonData.Slice(keyStart + key.Length).IndexOf(':') + keyStart + key.Length + 1; | |
| int valueEnd = jsonData.Slice(valueStart).IndexOf(','); | |
| if (valueEnd == -1) // If no comma, this is the last value | |
| { | |
| valueEnd = jsonData.Slice(valueStart).IndexOf('}'); | |
| } | |
| // Extract and print the value | |
| ReadOnlySpan<char> value = jsonData.Slice(valueStart, valueEnd); | |
| Console.WriteLine(value.ToString().Trim('"')); // Remove quotes | |
| } | |
| public void ProcessJsonArray(ReadOnlySpan<char> jsonArray) | |
| { | |
| int currentIndex = 0; | |
| while (currentIndex < jsonArray.Length) | |
| { | |
| int start = jsonArray.Slice(currentIndex).IndexOf('{'); | |
| if (start == -1) break; // No more objects | |
| int end = jsonArray.Slice(currentIndex).IndexOf('}'); | |
| if (end == -1) break; // Incomplete object | |
| ReadOnlySpan<char> jsonObject = jsonArray.Slice(currentIndex + start, end - start + 1); | |
| ProcessJsonObject(jsonObject); | |
| currentIndex += end + 1; // Move past the current object | |
| } | |
| } | |
| private void ProcessJsonObject(ReadOnlySpan<char> jsonObject) | |
| { | |
| // Simple key-value extraction, assuming keys and values are properly formatted | |
| int colonIndex = jsonObject.IndexOf(':'); | |
| ReadOnlySpan<char> key = jsonObject.Slice(1, colonIndex - 2); // Skipping surrounding quotes | |
| ReadOnlySpan<char> value = jsonObject.Slice(colonIndex + 1).Trim(); // Extract value and trim | |
| Console.WriteLine($"Key: {key.ToString()}, Value: {value.ToString()}"); | |
| } | |
| public void ParseJson(ReadOnlySpan<char> jsonData) | |
| { | |
| int start = 0; | |
| while (start < jsonData.Length) | |
| { | |
| int objectStart = jsonData.Slice(start).IndexOf('{'); | |
| if (objectStart == -1) break; | |
| int objectEnd = jsonData.Slice(start).IndexOf('}'); | |
| if (objectEnd == -1) break; | |
| ReadOnlySpan<char> jsonObject = jsonData.Slice(start + objectStart, objectEnd - objectStart + 1); | |
| ProcessJsonObject(jsonObject); | |
| start += objectEnd + 1; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment