1

In the context of converting to and from JSON:

perhaps the integer's below are just marking array index? Yet it's entirely possible to send 1,1,1 so it's not an index. the "1" might, perhaps, indicate a "depth" then?

PS /home/nicholas/powershell> 
PS /home/nicholas/powershell> ConvertTo-Json @(1)  
[
  1
]
PS /home/nicholas/powershell> 
PS /home/nicholas/powershell> ConvertTo-Json @(1,a)
ParserError: 
Line |
   1 |  ConvertTo-Json @(1,a)
     |                     ~
     | Missing expression after ','.

PS /home/nicholas/powershell> 
PS /home/nicholas/powershell> ConvertTo-Json @(1,2)
[
  1,
  2
]
PS /home/nicholas/powershell> 
PS /home/nicholas/powershell> ConvertTo-Json @(a)  
a: The term 'a' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
[]
PS /home/nicholas/powershell> 

why are integers okay:

PS /home/nicholas/powershell> 
PS /home/nicholas/powershell> ConvertTo-Json @(1,3,9)
[
  1,
  3,
  9
]
PS /home/nicholas/powershell> 

but not even a single char?

Neither it seems are String data acceptable.

2
  • 2
    JSON has no concept of a char type, only strings: ConvertTo-Json @(1,'a') Commented Nov 18, 2020 at 20:23
  • thx, that answers my question (such as it is) Commented Nov 18, 2020 at 20:24

1 Answer 1

3

PowerShell doesn't have any syntax for defining character literals, and bare words (like the a in your example) are interpreted as commands, as the error indicates.

If you want to pass the a single [char] a as a value, there are a number of options:

# Convert single-char string to char
[char]'a'
# or
'a' -as [char]

# Index into string
'a'[0]

# Convert from numberic value
97 -as [char]

So you could do something like this:

PS ~> ConvertTo-Json @(1,'a'[0])
[
    1,
    "a"
]

But as you'll notice, the resulting JSON appears to have converted the [char] back into a string - and that's because JSON's grammar doesn't have [char]'s either.

From RFC 8259 §3:

A JSON value MUST be an object, array, number, or string [...]

So converting from [string] to [char] is in fact completely redundant:

PS ~> ConvertTo-Json @(1,'a')
[
    1,
    "a"
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.