Ruby:访问元素

时间:2015-11-29 14:54:47

标签: ruby ruby-on-rails-4

我有

形式的输出
String date = "2015-01-01T00:00:00";
String sourceFormat = "yyyy-MM-dd'T'HH:mm:ss";
String targetFormat = "MM/dd/yyyy";
    SimpleDateFormat sdf = new SimpleDateFormat(sourceFormat);
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date strDate = new Date();

    try {
        strDate = sdf.parse(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    SimpleDateFormat sdf2 = new SimpleDateFormat(targetFormat);
    sdf2.setTimeZone(TimeZone.getDefault()); // Phone is set to GMT - 6 Hours America
    return sdf2.format(strDate);

存储在变量{\"id\":\"anon\",\"source\":\"abc\",\"word_count_message\":\"There were 268 words\"}"

我需要访问字段" word_count"

x

打印

x.inspect 

"{\"id\":\"anon\",\"source\":\"abc\",\"word_count\":268}" 打印x["word_count"]而不是word_count

我在这里缺少什么?

2 个答案:

答案 0 :(得分:1)

h = JSON.parse(x)
puts h["word_count_message"] to get the result.

答案 1 :(得分:0)

我确信有更简洁的方法来实现这一目标,但这有效:

h = Hash[x.tr('"{}\\', '').split(",").collect{|kv| [kv.split(":")[0], kv.split(":")[1]]}]

我拿出了双引号,括号和额外的\。然后我使用逗号作为分隔符将其拆分为数组。然后我使用:作为分隔符将该数组的每个元素更改为一个2元素的键/值数组。然后我把整个事情变成Hash

p h
p h["word_count_message"]

输出:

{"id"=>"anon", "source"=>"abc", "word_count_message"=>"There were 268 words"}
"There were 268 words"