我正在尝试从此JSON中提取数据,但是当我输入[0]时,它会返回'{'&如果我输入[“tweets0”],我什么也得不到。我错过了一些非常明显的东西吗?
我正在使用Ruby& MultiJson gem,如果改变了什么。
{
"tweets0": [
{
"content": "Test1",
"time": "2015/08/16 7:43 PM"
}
],
"tweets1": [
{
"content": "Test2",
"time": "2015/08/16 7:44 PM"
}
],
"tweets2": [
{
"content": "Test3",
"time": "2015/08/16 7:44 PM"
}
],
"tweets3": [
{
"content": "Test3",
"time": "2015/08/16 7:46 PM"
}
],
"tweets4": [
{
"content": "Test",
"time": "2015/08/16 7:45 PM"
}
],
"tweets5": [
{
"content": "3",
"time": "2015/08/16 7:48 PM"
}
],
"tweets6": [
{
"content": "3",
"time": "2015/08/16 7:48 PM"
}
],
"tweets7": [
{
"content": "3213",
"time": "2015/08/16 7:49 PM"
}
],
"tweets8": [
{
"content": "3213",
"time": "2015/08/16 7:49 PM"
}
],
"tweets9": [
{
"content": "23",
"time": "2015/08/16 7:50 PM"
}
],
"tweets10": [
{
"content": "23",
"time": "2015/08/16 7:49 PM"
}
],
"tweets11": [
{
"content": "3",
"time": "2015/08/16 7:53 PM"
}
],
"tweets12": [
{
"content": "34",
"time": "2015/08/16 7:53 PM"
}
],
"tweets13": [
{
"content": "25",
"time": "2015/08/16 7:53 PM"
}
],
"tweets14": [
{
"content": "right",
"time": "2015/08/16 7:52 PM"
}
]
}
答案 0 :(得分:2)
如果[0]返回' {',那表明Ruby并不是将JSON视为JSON对象,而是将其视为字符串。
也许你需要.load()
你的JSON?
答案 1 :(得分:0)
为什么不使用Ruby内置的标准json
库?
require 'json'
a = JSON.parse(your_json_data)
a["tweets0"] #=> [{"content"=>"Test1", "time"=>"2015/08/16 7:43 PM"}]
答案 2 :(得分:0)
使用MultiJson
加载数据后> require 'multi_json'
> json = MultiJson.load('{"tweets0": [{"content": "Test1","time": "2015/08/16 7:43 PM"}]}')
=> {"tweets0"=>[{"content"=>"Test1", "time"=>"2015/08/16 7:43 PM"}]}
然后您可以通过名称访问哈希元素:
> json['tweets0']
=>[{"content"=>"Test1", "time"=>"2015/08/16 7:43 PM"}]
要访问数组的元素:
> json['tweets0'].first
=> {"content"=>"Test1", "time"=>"2015/08/16 7:43 PM"}