(如果我应该说UTF8而不是Unicode,很抱歉.)

我已经遇到了this question个人,但几分钟后就想不通了.

这个问题的出发点和我的问题如下

import Data.Aeson
import qualified Data.Text.Encoding as E (encodeUtf8)
import qualified Data.ByteString.Lazy.Char8 as C8 (pack)
import qualified Data.Text as T (pack)

main :: IO ()
main = do
  print (foo "{ \"foo\": \"bar\"}" :: Maybe Value)
  print (foo "{ \"foo\": \"bòz\"}" :: Maybe Value)
  where
    foo = decode . C8.pack

将打印

Just (Object (fromList [("foo",String "bar")]))
Nothing

答案和 comments 都提到了利用Data.Text.Encoding中的encodeUtf8的解决方案.但如何做到呢?

  • C8.pack等于String -> ByteString
  • E.encodeUtf8等于Text -> ByteString
  • "{ \"foo\": \"bòz\"}"等于String

所以我想,如果我想用E.encodeUtf8,我需要go 掉C8.pack,作为类型为String -> Text的函数,而T.pack似乎就是这样一个函数.然而,以下几点:

import Data.Aeson
import qualified Data.Text.Encoding as E (encodeUtf8)
import qualified Data.ByteString.Lazy.Char8 as C8 (pack)
import qualified Data.Text as T (pack)

main :: IO ()
main = do
  print (foo "{ \"foo\": \"bar\"}" :: Maybe Value)
  print (foo "{ \"foo\": \"bòz\"}" :: Maybe Value)
  where
    foo = decode . E.encodeUtf8 . T.pack

编译失败,出现错误

    • Couldn't match type ‘bytestring-0.11.5.3:Data.ByteString.Internal.Type.ByteString’
                     with ‘Data.ByteString.Lazy.Internal.ByteString’
      Expected: Data.Text.Internal.Text
                -> Data.ByteString.Lazy.Internal.ByteString
        Actual: Data.Text.Internal.Text
                -> bytestring-0.11.5.3:Data.ByteString.Internal.Type.ByteString
      NB: ‘Data.ByteString.Lazy.Internal.ByteString’
            is defined in ‘Data.ByteString.Lazy.Internal’
          ‘bytestring-0.11.5.3:Data.ByteString.Internal.Type.ByteString’
            is defined in ‘Data.ByteString.Internal.Type’
    • In the first argument of ‘(.)’, namely ‘E.encodeUtf8’
      In the second argument of ‘(.)’, namely ‘E.encodeUtf8 . T.pack’
      In the expression: decode . E.encodeUtf8 . T.pack
   |
11 |     foo = decode . E.encodeUtf8 . T.pack
   |                    ^^^^^^^^^^^^

推荐答案

错误消息是,THA encodeUtf8生成严格的字节串,而decode期望产生懒惰的字节串.您可能可以通过使用延迟版本来修复它,例如,通过更改导入:

import qualified Data.Text.Lazy.Encoding as E (encodeUtf8)
import qualified Data.Text.Lazy as T (pack)

Json相关问答推荐

在Go中,当字段可以根据其他字段具有不同的类型时,什么是正确的方法来卸载JSON?

使用Jolt变换转换JsonArray以将关键字转移到内部JsonArray中

从JSON格式提取数据时分隔通用名称

如何在Power BI中集成API和JSON数据后将数据转换为表?

在ConvertFrom-Json之后需要从PowerShell对象中获取数据

在Zig中解析JSON失败

组合不同属性的Jolt Spec

如何使用模式注册中心创建从主题中取消本地化的ks qlDB表?

当由.sh脚本执行时,AWS查询字符串不会提取任何数据

使用 jolt 变换压平具有公共列 JSON 的复杂嵌套

转换为Json时忽略内部对象中的数组

如何使NiFi将数据库单列中的多个值转化为Solr索引中的数组?

如何在 JSonPath 中按值查找列表中的所有元素

在 PostgreSQL 中 Select 分层 JSON 作为表

将 JSON 文件放在哪里以在 Angular 8 应用程序中加载静态 JSON 数据?

Powershell - 如何从 JSON 中删除/过滤元素但保留其余部分?

无法向 Json 数组添加新元素

Angularjs访问本地json文件

使用适用于 Python 的 Google API - 我从哪里获取 client_secrets.json 文件?

按键值过滤 JSON