j - 使用 pjson 库获取雅虎股票报价
问题描述
我开始学习 J,所以我有一个关于使用 pjson 库(J 8.0.7 beta,Windows 10)读取 JSON 的简单函数的基本问题:
load 'web/gethttp'
load 'convert/pjson'
stock=: 3 : 0
jsonstr =: gethttp 'https://query1.finance.yahoo.com/v7/finance/quote?symbols=',y
dp =: dec_pjson_ jsonstr
)
我不知道如何使用基本动词(> 或 &.> 递归地达到我想要的值)从解码的 JSON 中搜索并获取值或将结果拆箱到“dp”中。我怎样才能做到这一点?
我用“原始”JSON字符串完成了它,但是以一种(我怀疑)愚蠢的方式(模错误检查):
load 'web/gethttp'
stock=: 3 : 0
jsonstr =: gethttp 'https://query1.finance.yahoo.com/v7/finance/quote?symbols=',y
sdp=: ;: jsonstr NB. boxes the raw JSON string in word cells
matchstr=:('regularMarketPrice' & e.) &.> sdp NB. find string on each cell - return cells with 1's for each matching char
summatch=:+/ &.> matchstr NB. sum the 1's in each cell
vec=: > summatch NB. unbox to a vector
index =: (i. >./) vec NB. find the index of the biggest number - is our searched string
tit=: index } sdp NB. Use index to get the title
val =: (index+2) } sdp NB. Use index to get the value
tit,val
)
stock 'PETR4.SA'
如果无法使用 pjson,是否有更好的方法来表达原始字符串版本?
提前致谢!
解决方案
我想我会这样处理(NB.
代码后面有注释):
stock_base_=: 4 : 0 NB. I would make it dyadic so that I could specify the line I wanted displayed
jsonstr =. gethttp 'https://query1.finance.yahoo.com/v7/finance/quote?symbols=',y
qname=. <x NB. Box the x argument to allow imput to search for the line required
dp =. dec_pjson_ jsonstr NB. Same approach as you
dp =.{. >> {: {.}:{. > }. {. dp NB. Strip off information that I don't need to create a two column table
qname ((= {."1) # ] )dp NB. Search the first column of the table for my x argument and return that line as a result
)
'exchange' stock 'PETR4.SA'
┌────────┬───┐
│exchange│SAO│
└────────┴───┘
'symbol' stock 'PETR4.SA'
┌──────┬────────┐
│symbol│PETR4.SA│
└──────┴────────┘
'regularMarketDayHigh' stock 'PETR4.SA'
┌────────────────────┬─────┐
│regularMarketDayHigh│19.81│
└────────────────────┴─────┘
该行dp =.{. >> {: {.}:{. > }. {. dp
是最让我烦恼的行,因为可能有更好的方法来清理dec_pjson_
已生成的表,但这有效。
推荐阅读
- angular - 多次发出使用 RXJS 主题的窗口调整大小事件
- java - 如何获取 .txt 文件中每个单词的长度
- java - Java - DTO 接口 target.targetSource 值 null ->“某些值”
- javascript - 如何将数字附加到相关的字符串 JS
- python - Jupyter 在 docker 容器中启动内核?
- vbscript - 有没有办法使用 vbs 将驱动器的每个文件和文件夹移动到驱动器本身的文件夹中
- php - 在 php Codeigniter 中上传用户个人资料图片
- python - 对对象的调用在另一个文件中不起作用
- reactjs - React - useEffect 即使没有变化
- amazon-web-services - AWS 按特定用户收取费用