0

初学者 Clojurist 在这里。我正在尝试使用 Clojurescript 和cljs-http库解析 JSON 文件。我使用以下函数有奇怪的行为:

(defn make-remote-call [endpoint]
  (go (let [response (<! (http/get endpoint))]
    (js/console.log (:body response)))))

这会将 json 文件打印到控制台,但我会收到以下错误消息:

XML Parsing Error: not well-formed
Location: file:///***U2328710-data.json
Line Number 1, Column 1: 

我尝试过的事情:

  • JSON 文件通过http://jsonlint.com成功,但https://jsonformatter.curiousconcept.com/解析文件并说Error:Invalid encoding, expecting UTF-8, UTF-16 or UTF-32.[Code 29, Structure 0]
  • 当我在 Apache 服务器上部署时出现同样的问题。我的 .htaccess 文件已正确设置为将 content-header 发送到 application/json 并将 charset 发送到 utf-8 (虽然我已经读过我应该发送大写的 UTF-8,但无法做到这一点)
  • 我可以毫无问题地解析具有相同功能的 XML 文件
  • 我可以使用已弃用的方法毫无问题地解析相同的 JSON 文件js/XMLHttpRequest

没有想法了-有人可以帮忙吗?我想知道 cljs-http 是否不理解它是一个 json 文件,我可以强制它/也许覆盖标头吗?谢谢,

4

1 回答 1

2

我认为这要么是您的 JSON 文件中的一些编码问题,要么是cljs-http库之外的一些其他问题。我使用创建的新项目运行了一个小测试lein new figwheel json-client,并将依赖项添加[cljs-http "0.1.46"]project.clj

对于一个有效的 JSON 文件,我访问了https://api.github.com/users/clojure/repos并将内容保存resources/public/repos.json在项目文件夹中。

我的core.clj文件内容是:

(ns json-client.core
  (:require-macros [cljs.core.async.macros :refer [go]])
  (:require [cljs-http.client :as http]
            [cljs.core.async :refer [<!]]))

(enable-console-print!)

(defn make-remote-call [endpoint]
  (go (let [response (<! (http/get endpoint))]
        (js/console.log (clj->js (:body response)))))) ;; NOTE: cljs->js

(defonce app-state (atom {:text "Hello world!"}))

;; This content is served by figwheel, configured in project.clj
(make-remote-call "http://0.0.0.0:3449/repos.json")

(defn on-js-reload []
  ;; optionally touch your app-state to force rerendering depending on
  ;; your application
  ;; (swap! app-state update-in [:__figwheel_counter] inc)
)

注意clj->js:记录到控制台(使用)的行中只有一个更改,但仅此而已。

...当我用它启动项目时,lein figwheel它需要几秒钟并使用项目启动一个新的浏览器选项卡,在控制台上我可以看到它记录了 JSON 文件的内容:

在此处输入图像描述

于 2019-07-12T04:50:03.110 回答