Skip to content

JSON strings with quotes cause escaping issues #39

@konard

Description

@konard

🐛 Bug Description

JSON strings containing quotes and special characters get corrupted when passed through command-stream's shell interpolation. This makes it impossible to reliably work with JSON data using shell commands, affecting configuration files, API responses, and data processing scripts.

🔴 Impact

  • Configuration management - Can't write JSON config files reliably
  • Data processing - JSON data gets corrupted during shell operations
  • API integrations - Can't pass JSON payloads through shell commands
  • Build scripts - Package.json and similar files can't be manipulated

📝 Detailed Problem Analysis

JSON inherently contains quotes for string values, which conflict with shell quoting mechanisms:

  1. Nested quotes in JSON values break shell parsing
  2. Escaped quotes get double-escaped or mangled
  3. Special characters like backticks and dollar signs cause additional issues
  4. JSON structure can be broken, making it unparseable

🔄 Reproduction

const jsonData = {
  name: "Test Project",
  description: "A project with \\"quotes\\" and 'apostrophes'",
  scripts: {
    test: "echo \\"Running tests\\"",
    build: "node build.js --env='production'"
  },
  config: {
    special: "Value with \`backticks\` and $variables"
  }
};

const jsonString = JSON.stringify(jsonData, null, 2);

// ❌ This corrupts the JSON
await $\`echo '\${jsonString}' > package.json\`;

// JSON becomes invalid and can't be parsed back

✅ Expected Behavior

JSON should be written exactly as formatted, maintaining valid JSON syntax.

❌ Actual Behavior

  • JSON structure gets corrupted
  • Quotes are escaped incorrectly
  • Resulting file contains invalid JSON
  • JSON.parse() fails on the output

🔧 Workaround

// ✅ Use fs.writeFile for JSON data
await fs.writeFile('package.json', JSON.stringify(data, null, 2));

🎯 Root Cause

Shell interpretation of quotes within JSON strings creates multiple layers of escaping that conflict with each other.

🔗 References

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions