【发布时间】:2015-04-01 02:30:24
【问题描述】:
我正在做一个从 Riot Games API 解析 JSON 的项目,但遇到了麻烦。我对此很陌生,所以请耐心等待:
API 返回 JSON,例如:
{"forcinit":{"id":35979437,"name":"F O R C I N it","profileIconId":576,"summonerLevel":30,"revisionDate":1427753158000}}
在我的代码中,我有以下内容:
#lang racket
(require
racket/gui/base
net/url
json
racket/format
)
; --- Query API
(define api-request "https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/SUMMONER_NAME?api_key=8864143b-a987-45a8-b49d-53c0a7677100")
(define (query-for-summoner name)
(define summoner-request (string->url (string-replace api-request "SUMMONER_NAME" name)))
; Define request parameters, setup for output
(define sh (get-pure-port summoner-request #:redirections 5))
(define summoner-hash-str (port->string sh))
(define summoner-hash-json (string->jsexpr summoner-hash-str))
(define summoner (hash-ref summoner-hash-json name))
;I can't figure out how to make it so the "name" in the above line gets evaluted to the input, but read in as a literal
;in order for it to correctly be identified for the hash. as of now, for example if i type in "Dyrus" in the gui box
; it says
;hash-ref: no value found for key
;key: "Dyrus"
;yet if i replace name with 'dyrus it works correctly.
;If you know of a way to take a variable and have racket read it as a literal, I would love to hear it.
;I've tried serching the documentation and googling but I can't seem to find what I'm looking for.
(define summoner-id (hash-ref summoner 'id))
(define summoner-name (hash-ref summoner 'name))
(define summoner-icon (hash-ref summoner 'profileIconId))
(define summoner-level (hash-ref summoner 'summonerLevel))
(printf "Results for: ~a\n" summoner-name)
(printf "- ID: ~a\n" summoner-id)
(printf "- Icon ID: ~a\n" summoner-icon)
(printf "- Level: ~a\n" summoner-level)
)
; --- Build Frame
(define frame (new frame%
[label "League of Legends Statistics Tracker"]
[width 300]
[height 300]))
(send frame show #t)
(define msg (new message%
[parent frame]
[label "Welcome to the LoL Stats Tracker."]))
(define sn-input (new text-field%
[parent frame]
[label "Summoner Name: "]
[init-value "omithegreat"]
[callback (lambda(f ev)
(send f get-value))
]))
(define submit-button (new button%
[parent frame]
[label "Search"]
[callback (lambda (button event)
(let ([v (send sn-input get-value)])
(query-for-summoner v))
(send msg set-label "Searching for user..."))]))
我编辑了我的 riot API 私钥;当我用我在 gui 框中输入的任何名称替换 name 时,代码工作正常,例如,如果我搜索 dyrus,然后我替换“(定义召唤者(hash-ref 召唤者哈希 json 名称))” 和 (定义召唤师(hash-ref 召唤师-哈希-json 'dyrus))
它工作正常。 有没有办法让我输入名称,然后将名称字符串转换为文字,就像前面带有 ' 的相同字符串?
【问题讨论】:
-
string->symbol -
这与您的问题没有直接关系,但是在您的提交按钮回调中,您应该在
query-for-summoner之前设置标签之前 而不是之后。 -
为了挑剔,可能是您无法搜索答案的原因,“文字”是仅存在于源代码中的东西;它是值的文字表示(
1和"dyson"也是文字)。无法在运行时将值转换为文字。您正在寻找的概念是“符号”。