我正在尝试从哈希表(键,值)数组中的文件导入/读取数据,但无法执行,因为未使用默认分配符号( = )代替冒号( : ) .我尝试了不同的方法来读取数据,但是 powershell 每次都会给我一个错误。
数据(在此处被截断)采用以下格式(注意等号被替换为:
[{"name":"Alex","IQ":"A+"},{"name":"Steve","IQ":"60"},{"name":"Lisa","IQ":"90"},{"name":"Jackie","IQ":"B"}]
如何将这些数据读入数组或变量中,以便我可以使用它?这是错误消息:
> @a = [{"name":"Alex","IQ":"A+"},{"name":"Steve","IQ":"60"},{"name":"Lisa","IQ":"90"},{"name":"Jackie","IQ":"B"}]
At line:1 char:7
+ @a = [{"name":"Alex","IQ":"A+"},{"name":"Steve","IQ":"60"},{"name":"L ...
+ ~
Missing type name after '['.
At line:1 char:14
+ @a = [{"name":"Alex","IQ":"A+"},{"name":"Steve","IQ":"60"},{"name":"L ...
+ ~~~~~~~
Unexpected token ':"Alex"' in expression or statement.
At line:1 char:21
+ @a = [{"name":"Alex","IQ":"A+"},{"name":"Steve","IQ":"60"},{"name":"L ...
+ ~
Missing argument in parameter list.
At line:1 char:40
+ @a = [{"name":"Alex","IQ":"A+"},{"name":"Steve","IQ":"60"},{"name":"L ...
+ ~~~~~~~~
Unexpected token ':"Steve"' in expression or statement.
At line:1 char:48
+ @a = [{"name":"Alex","IQ":"A+"},{"name":"Steve","IQ":"60"},{"name":"L ...
+ ~
Missing argument in parameter list.
At line:1 char:67
+ ... ":"Alex","IQ":"A+"},{"name":"Steve","IQ":"60"},{"name":"Lisa","IQ":"9 ...
+ ~~~~~~~
Unexpected token ':"Lisa"' in expression or statement.
At line:1 char:74
+ ... :"Alex","IQ":"A+"},{"name":"Steve","IQ":"60"},{"name":"Lisa","IQ":"90 ...
+ ~
Missing argument in parameter list.
At line:1 char:93
+ ... "Steve","IQ":"60"},{"name":"Lisa","IQ":"90"},{"name":"Jackie","IQ":"B ...
+ ~~~~~~~~~
Unexpected token ':"Jackie"' in expression or statement.
At line:1 char:102
+ ... Steve","IQ":"60"},{"name":"Lisa","IQ":"90"},{"name":"Jackie","IQ":"B" ...
+ ~
Missing argument in parameter list.
At line:1 char:1
+ @a = [{"name":"Alex","IQ":"A+"},{"name":"Steve","IQ":"60"},{"name":"L ...
+ ~~
The splatting operator '@' cannot be used to reference variables in an expression. '@a' can be used only as an
argument to a command. To reference variables in an expression use '$a'.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingTypename
最佳答案
您的输入似乎是 JSON,因此您需要:
'...'
中(假设要逐字使用该值)。ConvertFrom-Json
将字符串解析为对象图小命令:$arrayOfObjects = ConvertFrom-Json '[{"name":"Alex","IQ":"A+"},{"name":"Steve","IQ":"60"},{"name":"Lisa","IQ":"90"},{"name":"Jackie","IQ":"B"}]'
$arrayOfObjects
然后包含一个数组 [pscustomobject]
表示 JSON 输入的实例;如果你输出 $arrayOfObjects
, 你会看到的:name IQ
---- --
Alex A+
Steve 60
Lisa 90
Jackie B
[1] 您问题中作业的 RHS (
=
) 以未加引号的 [
开头,这意味着 PowerShell 以表达式模式解析它,因此期望 [
成为类型文字的一部分,例如 [string]
- 参见概念 about_Parsing帮助主题。另外,请注意印记
@
从不用于变量赋值(必须使用 $
),仅在 splatting 的上下文中使用;也就是说,使用 $var = ...
, 从不 @var = ...
.
关于arrays - Powershell - 无法以哈希表数组的形式将数据从文件导入到变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67679113/