Skip to main content
Glama

json_parser

Process JSON by parsing, validating, querying specific fields using dot-notation, or summarizing structure.

Instructions

Parse, validate, and query JSON data.

Modes:

  • "parse": Parse a JSON string and return it formatted.

  • "query": Extract a specific field using dot-notation (e.g., "data.users[0].name").

  • "validate": Check if a string is valid JSON and describe its structure.

  • "summarize": Return a schema-like summary of a JSON object's structure.

Examples:

  • Parse: '{"a":1,"b":2}' → pretty-printed object

  • Query: '{"users":[{"name":"Alice"}]}' with path "users[0].name" → "Alice"

  • Validate: '{"a":1}' → {"valid": true, "type": "object", "keys": ["a"]}

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
jsonYesThe JSON string to process.
operationNoThe operation to perform on the JSON data.parse
pathNoDot-notation path for query mode (e.g., "users[0].name").

Implementation Reference

  • The main handler function for the json_parser tool. It accepts a JSON string and an operation (parse/query/validate/summarize), parses the JSON, and executes the requested operation. Uses auxiliary helper functions queryJson and summarizeStructure.
    async ({ json, operation, path: queryPath }) => {
      try {
        let parsed: unknown;
    
        // Attempt to parse JSON
        try {
          parsed = JSON.parse(json);
        } catch (parseErr: any) {
          return {
            content: [
              {
                type: "text" as const,
                text: JSON.stringify(
                  {
                    valid: false,
                    error: parseErr.message,
                    hint: "Check for trailing commas, unquoted keys, or single quotes.",
                  },
                  null,
                  2
                ),
              },
            ],
          };
        }
    
        switch (operation) {
          case "parse": {
            return {
              content: [
                {
                  type: "text" as const,
                  text: JSON.stringify(parsed, null, 2),
                },
              ],
            };
          }
    
          case "query": {
            if (!queryPath) {
              return {
                content: [
                  {
                    type: "text" as const,
                    text: 'Error: "path" parameter is required for query operation.',
                  },
                ],
                isError: true,
              };
            }
    
            const result = queryJson(parsed, queryPath);
            return {
              content: [
                {
                  type: "text" as const,
                  text: JSON.stringify(
                    {
                      path: queryPath,
                      found: true,
                      value: result,
                      type: Array.isArray(result)
                        ? "array"
                        : result === null
                          ? "null"
                          : typeof result,
                    },
                    null,
                    2
                  ),
                },
              ],
            };
          }
    
          case "validate": {
            return {
              content: [
                {
                  type: "text" as const,
                  text: JSON.stringify(
                    {
                      valid: true,
                      type: Array.isArray(parsed)
                        ? "array"
                        : parsed === null
                          ? "null"
                          : typeof parsed,
                      ...(Array.isArray(parsed)
                        ? { length: parsed.length, itemTypes: [...new Set(parsed.map((i) => typeof i))] }
                        : typeof parsed === "object" && parsed !== null
                          ? { keys: Object.keys(parsed as object), keyCount: Object.keys(parsed as object).length }
                          : { value: parsed }),
                    },
                    null,
                    2
                  ),
                },
              ],
            };
          }
    
          case "summarize": {
            const summary = summarizeStructure(parsed);
            return {
              content: [
                {
                  type: "text" as const,
                  text: JSON.stringify(summary, null, 2),
                },
              ],
            };
          }
    
          default:
            return {
              content: [
                {
                  type: "text" as const,
                  text: `Error: Unknown operation '${operation}'.`,
                },
              ],
              isError: true,
            };
        }
      } catch (err: any) {
        return {
          content: [
            {
              type: "text" as const,
              text: `JSON Parser Error: ${err.message}`,
            },
          ],
          isError: true,
        };
      }
    }
  • Zod schema definitions for the json_parser tool: json (string), operation (enum: parse/query/validate/summarize, defaults to parse), and path (optional string for query mode).
    {
      json: z.string().describe("The JSON string to process."),
      operation: z
        .enum(["parse", "query", "validate", "summarize"])
        .default("parse")
        .describe("The operation to perform on the JSON data."),
      path: z
        .string()
        .optional()
        .describe(
          'Dot-notation path for query mode (e.g., "users[0].name").'
        ),
    },
  • The registerJsonParserTool function that registers the tool with the MCP server using server.tool("json_parser", ...). Also called from src/index.ts at line 54.
    export function registerJsonParserTool(server: McpServer): void {
      server.tool(
        "json_parser",
        `Parse, validate, and query JSON data.
    
    Modes:
      - "parse": Parse a JSON string and return it formatted.
      - "query": Extract a specific field using dot-notation (e.g., "data.users[0].name").
      - "validate": Check if a string is valid JSON and describe its structure.
      - "summarize": Return a schema-like summary of a JSON object's structure.
    
    Examples:
      - Parse:   '{"a":1,"b":2}' → pretty-printed object
      - Query:   '{"users":[{"name":"Alice"}]}' with path "users[0].name" → "Alice"
      - Validate: '{"a":1}' → {"valid": true, "type": "object", "keys": ["a"]}`,
        {
          json: z.string().describe("The JSON string to process."),
          operation: z
            .enum(["parse", "query", "validate", "summarize"])
            .default("parse")
            .describe("The operation to perform on the JSON data."),
          path: z
            .string()
            .optional()
            .describe(
              'Dot-notation path for query mode (e.g., "users[0].name").'
            ),
        },
        async ({ json, operation, path: queryPath }) => {
          try {
            let parsed: unknown;
    
            // Attempt to parse JSON
            try {
              parsed = JSON.parse(json);
            } catch (parseErr: any) {
              return {
                content: [
                  {
                    type: "text" as const,
                    text: JSON.stringify(
                      {
                        valid: false,
                        error: parseErr.message,
                        hint: "Check for trailing commas, unquoted keys, or single quotes.",
                      },
                      null,
                      2
                    ),
                  },
                ],
              };
            }
    
            switch (operation) {
              case "parse": {
                return {
                  content: [
                    {
                      type: "text" as const,
                      text: JSON.stringify(parsed, null, 2),
                    },
                  ],
                };
              }
    
              case "query": {
                if (!queryPath) {
                  return {
                    content: [
                      {
                        type: "text" as const,
                        text: 'Error: "path" parameter is required for query operation.',
                      },
                    ],
                    isError: true,
                  };
                }
    
                const result = queryJson(parsed, queryPath);
                return {
                  content: [
                    {
                      type: "text" as const,
                      text: JSON.stringify(
                        {
                          path: queryPath,
                          found: true,
                          value: result,
                          type: Array.isArray(result)
                            ? "array"
                            : result === null
                              ? "null"
                              : typeof result,
                        },
                        null,
                        2
                      ),
                    },
                  ],
                };
              }
    
              case "validate": {
                return {
                  content: [
                    {
                      type: "text" as const,
                      text: JSON.stringify(
                        {
                          valid: true,
                          type: Array.isArray(parsed)
                            ? "array"
                            : parsed === null
                              ? "null"
                              : typeof parsed,
                          ...(Array.isArray(parsed)
                            ? { length: parsed.length, itemTypes: [...new Set(parsed.map((i) => typeof i))] }
                            : typeof parsed === "object" && parsed !== null
                              ? { keys: Object.keys(parsed as object), keyCount: Object.keys(parsed as object).length }
                              : { value: parsed }),
                        },
                        null,
                        2
                      ),
                    },
                  ],
                };
              }
    
              case "summarize": {
                const summary = summarizeStructure(parsed);
                return {
                  content: [
                    {
                      type: "text" as const,
                      text: JSON.stringify(summary, null, 2),
                    },
                  ],
                };
              }
    
              default:
                return {
                  content: [
                    {
                      type: "text" as const,
                      text: `Error: Unknown operation '${operation}'.`,
                    },
                  ],
                  isError: true,
                };
            }
          } catch (err: any) {
            return {
              content: [
                {
                  type: "text" as const,
                  text: `JSON Parser Error: ${err.message}`,
                },
              ],
              isError: true,
            };
          }
        }
      );
    }
  • Helper function queryJson that navigates a JSON object using a dot-notation path, supporting array index notation like "users[0].name".
    export function queryJson(data: unknown, path: string): unknown {
      const parts = path.replace(/\[(\d+)\]/g, ".$1").split(".");
    
      let current: unknown = data;
    
      for (const part of parts) {
        if (part === "") continue;
    
        if (
          current === null ||
          current === undefined ||
          typeof current !== "object"
        ) {
          return undefined;
        }
    
        current = (current as Record<string, unknown>)[part];
      }
    
      return current;
    }
  • Helper function summarizeStructure that generates a schema-like summary of a JSON value's structure, with a maximum depth of 5 levels.
    export function summarizeStructure(data: unknown, depth: number = 0): unknown {
      const MAX_DEPTH = 5;
      if (depth > MAX_DEPTH) return "[max depth reached]";
    
      if (data === null) return { type: "null" };
      if (typeof data !== "object") return { type: typeof data };
    
      if (Array.isArray(data)) {
        if (data.length === 0) return { type: "array", length: 0 };
        return {
          type: "array",
          length: data.length,
          itemSchema: summarizeStructure(data[0], depth + 1),
          ...(data.length > 1
            ? { sampleItems: 2, items: [summarizeStructure(data[0], depth + 1)] }
            : {}),
        };
      }
    
      const record = data as Record<string, unknown>;
      const keys = Object.keys(record);
      const schema: Record<string, unknown> = { type: "object", keys };
    
      if (keys.length > 0) {
        schema.properties = {};
        for (const key of keys.slice(0, 10)) {
          (schema.properties as Record<string, unknown>)[key] =
            summarizeStructure(record[key], depth + 1);
        }
        if (keys.length > 10) {
          (schema.properties as Record<string, unknown>)[
            "...andMore"
          ] = `${keys.length - 10} additional keys`;
        }
      }
    
      return schema;
    }
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Since no annotations are provided, the description fully bears the responsibility for behavioral disclosure. It explains the outcomes for each operation (e.g., pretty-printed object for parse, extraction for query, validation result, summary for summarize) and provides examples. It does not cover error handling (e.g., malformed JSON) or performance, which is a minor gap.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is concise, with a clear opening sentence followed by a well-structured list of modes and examples. Every sentence provides essential information without redundancy, and the most critical information is front-loaded.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool has three parameters, no output schema, and no annotations, the description is largely complete. It explains each mode's return, path notation, and provides examples. However, it does not clarify that 'path' is only relevant for query mode (though implied) or describe error behavior for invalid inputs, which prevents a perfect score.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 100% coverage, but the description significantly enriches understanding: it explains the enum 'operation' with four distinct modes, clarifies the dot-notation for 'path', and provides concrete examples demonstrating how parameters interact. The schema descriptions are minimal, so the description adds substantial value.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description starts with 'Parse, validate, and query JSON data', immediately stating the tool's resource (JSON data) and action verbs. It clearly distinguishes itself from sibling tools like text_transform, which handle general text transformations, by focusing specifically on JSON operations.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description lists four modes (parse, query, validate, summarize) with specific use cases and examples for each, guiding the agent on when to use each mode. However, it does not explicitly state when not to use this tool or provide alternatives among sibling tools, which would push it to a 5.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/vyshnavi-nandyala/mcp-toolkit-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server