json - ConvertFrom-Json 将小写 e 转换为大写字母(有时)

标签 json powershell

我正在 PowerShell 中处理 JSON 文件,似乎 ConvertFrom-Json 仅在某些(罕见)情况下更改其输入的大小写。

例如,当我这样做时:

$JsonStringSrc = '{"x":2.2737367544323206e-13,"y":1759,"z":33000,"width":664}' 
$JsonStringTarget = $JsonStringSrc | ConvertFrom-Json | ConvertTo-Json -Depth 100 -Compress
$JsonStringTarget 

它返回:

{"x":2.2737367544323206E-13,"y":1759,"z":33000,"width":664}

小写的 e 变成了大写的 E,在处理过程中验证正确的 I/O 时弄乱了我的哈希值。

这是预期的行为(可能是区域设置)吗? ConvertFrom-Json 是否有一个设置可以让我的输入单独用于输出?

最佳答案

问题在于 PowerShell 的 JSON 库输出 CLR float 的方式。通过从 JSON 进行转换,您可以将 JSON 字符串转换为具有数字和字符串等关联类型的 CLR/PowerShell 对象。转换回 JSON 会将该对象序列回 JSON,但使用 .NET 默认格式化程序配置来执行此操作。原始 JSON 文档中没有元数据来帮助转换。舍入错误和截断、元素顺序不同也可能发生在这里。

规范形式(散列时要使用的形式)的 JSON 规范如下:

MUST represent all non-integer numbers in exponential notation

  • including a nonzero single-digit significant integer part, and
  • including a nonempty significant fractional part, and
  • including no trailing zeroes in the significant fractional part (other than as part of a “.0” required to satisfy the preceding point), and
  • including a capital “E”, and
  • including no plus sign in the exponent, and
  • including no insignificant leading zeroes in the exponent

来源:https://gibson042.github.io/canonicaljson-spec/

尽管 JSON 规范支持这两个选项(eE)。

exponent
   ""
   'E' sign digits
   'e' sign digits

来源:https://www.crockford.com/mckeeman.html

您可以直接使用 Newtonsoft.Json 类并传入自定义转换器将对象转换为 JSON。

更好的解决方案可能是使用专门的格式化程序组件来直接操作现有的 JSON 文档,而无需先将其转换为 CLR 对象。

关于json - ConvertFrom-Json 将小写 e 转换为大写字母(有时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59695171/

相关文章:

powershell - 如何在FTP服务器中移动文件

java - 解析巨大的 json 响应

json - 如何使用来自 Alamofire 的 JSON 数据填充表格 View ?

powershell - 如何在 Azure Function 中安装 PowerShell 模块

powershell - 在 Windows 10 Powershell 中通过 F7 使命令历史弹出窗口工作

powershell - 为什么 PowerShell 5 在重命名后仍在寻找旧的 PowerShell Gallery 路径?

azure - 使用 Powershell CLI 获取 Azure VM 的 NSG

javascript - 如何使用 Javascript 更改 JSON 对象

iOS 异步任务卡住

javascript - 如何等待纹理完成从 Three.js 中的 JSON 模型加载?