json icon indicating copy to clipboard operation
json copied to clipboard

How to process key with colon and other characters?

Open dracorp opened this issue 4 years ago • 3 comments

I have an issue:

echo '{"scripts":{"build:apps":"build_apps.sh"}}' | json
{
  "scripts": {
    "build:apps": "build_apps.sh"
  }
}

Now, I want modify this value:

echo '{"scripts":{"build:apps":"build_apps.sh"}}' | json -e 'this.build:apps="foo"'
undefined:3
this.build:apps="foo"
          ^

SyntaxError: Unexpected token ':'
    at new Function (<anonymous>)
    at main (/Users/u537501/Projects/Projects-lsy/CrewApps/AzureDevOps/CrewPortal/src/LayoverApp/node_modules/json/lib/json.js:1365:27)
    at Object.<anonymous> (/Users/u537501/Projects/Projects-lsy/CrewApps/AzureDevOps/CrewPortal/src/LayoverApp/node_modules/json/lib/json.js:1764:5)
    at Module._compile (node:internal/modules/cjs/loader:1095:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1124:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:816:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
    at node:internal/main/run_main_module:17:47

How to handle colon? I've tried with backslash, double/single quotes.

The same situation is with minus:

echo '{"scripts":{"build-apps":"build_apps.sh"}}' | json -e 'this.build-apps="foo"'
undefined:3
this.build-apps="foo"
^^^^^^^^^^^^^^^

SyntaxError: Invalid left-hand side in assignment

or

echo '{"scripts":{"build-apps":"build_apps.sh"}}' | json -e 'this."build-apps"="foo"'
undefined:3
this."build-apps"="foo"
     ^^^^^^^^^^^^

SyntaxError: Unexpected string

The jq program parses those characters:

$ echo '{"scripts":{"build-apps":"build_apps.sh"}}' | jq '.scripts."build-apps"'
"build_apps.sh"

dracorp avatar Aug 12 '21 13:08 dracorp

json -e 'this["build:apps"]="foo"' should do the trick

mirkonz avatar Oct 28 '21 01:10 mirkonz

Nice trick, thank you. Where did the idea for this syntax come from?

dracorp avatar Oct 28 '21 06:10 dracorp

@dracorp https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors#bracket_notation

mstrater avatar Feb 24 '22 23:02 mstrater