[英]How can I get hash from string and then string from hash back in javascript
[英]How can I select keys from a hash in Ruby with a string of javascript?
我正在使用Ruby中的命令行工具進行工作,該工具可以分析來自各種來源的JSON並處理數據。 我希望用戶能夠將該工具與任何JSON源一起使用,因此gem從用戶提供的YAML文件中讀取一些基本配置,如下所示:
# config.yml
json_sources:
sourcea:
url: 'https://example.com/some/json/api.json'
list_key: 'response.items'
name_key: 'name'
sourceb:
url: 'https://otherexample.org/another/api.json'
list_key: ''
name_key: 'basics.name'
在此示例中,從https://example.com/some/json/api.json
返回的JSON如下所示:
{
"response": {
"items": [
{
"id": 1,
"name": 'Item 1'
},
{
"id": 2,
"name": 'Item 2'
}
]
}
}
來自https://otherexample.org/another/api.json
的JSON如下所示:
[
{
"basics": {
"name": "Other Item 1"
}
},
{
"basics": {
"name": "Other Item 2"
}
}
]
在每種情況下, url
是JSON的URI, list_key
是應在JSON中進行迭代的鍵, name_key
是我們要從每個對象獲取的鍵。 因此,我的問題是,在Ruby中,我應該如何解析list_key
和name_key
?
Ruby中是否有一些便捷的方法來獲取帶有一串javascript樣式選擇器的哈希中的鍵值,還是我自己應該為它編寫一個方法?
我最喜歡Javascript的一件事是可以使用object.property
以及object["property"]
訪問對象的屬性的方式。 在Ruby中,您只能使用hash["value"]
訪問hash["value"]
。
要回答您的問題,您將需要找到一種轉換list_key
和name_key
的方法,以便它可以在Ruby中使用。 做到這一點的最佳方法首先取決於您如何處理JSON的解析,但是我應該像將list_key
和name_key
拆分為一個name_key
數組然后訪問哈希值一樣簡單。
希望能有所幫助。
由於沒有人有更好的答案,所以我繼續寫了一個方法:
def get_value_from_selector(hash, selector_string)
selectors = selector_string.split '.'
selectors.each do |selector|
hash = hash[selector] if hash
end
hash
end
我這樣稱呼它:
raw_json_string = '{ "response": { "name": "foo" } }'
json = JSON.parse raw_json_string
x = get_value_from_selector json, 'response.name'
這將x
設置為'foo'
。
此方法有效,但不支持['square_bracket']
表示法或任何其他JavaScript。 我敢肯定,我可以修改該方法以在以后做,但是現在可以用了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.