首页 > 解决方案 > 使用 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,是否有更好的方法来表达原始字符串版本?

提前致谢!

标签: j

解决方案


我想我会这样处理(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_已生成的表,但这有效。


推荐阅读