使用pjson库获取Yahoo股票报价

时间:2018-07-27 18:04:25

标签: j

我开始学习J,所以我有一个基本问题,涉及一个简单的函数,该函数使用pjson库读取JSON(J 8.0.7 beta,Windows 10):

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的情况下,有没有更好的方法来表示原始字符串版本?

谢谢!

1 个答案:

答案 0 :(得分:2)

我想我会这样处理(代码中的注释遵循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_产生的表,但这行得通。