热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

将JSON转换为字符串或ruby中的散列。-ConvertJSONtostringorhashinruby

Ihavetried:我有尝试:requirenethttprequirejsonrequirepprequireuriurlhttp:xyz

I have tried:

我有尝试:

require 'net/http'
require 'json'
require 'pp'
require 'uri'

url = "http://xyz.com"
resp = Net::HTTP.get_response(URI.parse(url))
buffer = resp.body
result = JSON.parse(buffer)
#result.to_hash
    #pp result
puts result  

And got the output as:

输出为:

{"id"=>"ABC", "account_id"=>"123", "first_name"=> "PEUS" }

in JSON format but I only need the value of id to be printed as ABC.

以JSON格式,但我只需要将id的值打印为ABC。

1 个解决方案

#1


11  

Your incoming string in JSON would look like:

JSON格式的传入字符串如下:

{"id":"ABC","account_id":"123","first_name":"PEUS"}

After parsing with JSON it's the hash:

使用JSON解析后,它是散列:

{"id"=>"ABC", "account_id"=>"123", "first_name"=> "PEUS" }

So, I'd use:

所以,我使用:

hash = {"id"=>"ABC", "account_id"=>"123", "first_name"=> "PEUS" }
hash['id'] # => "ABC"

Here's a more compact version:

这里有一个更紧凑的版本:

require 'json'

json = '{"id":"ABC","account_id":"123","first_name":"PEUS"}'
hash = JSON[json]
hash['id'] # => "ABC"

Note I'm using JSON[json]. The JSON [] class method is smart enough to sense what the parameter being passed in is. If it's a string it'll parse the string. If it's an Array or Hash it'll serialize it. I find that handy because it allows me to write JSON[...] instead of having to remember whether I'm parsing or using to_json or something. Using it is an example of the first virtue of programmers.

请注意我用JSON(JSON)。JSON[]类方法足够智能,可以感知传入的参数是什么。如果它是一个字符串,它将解析这个字符串。如果是数组或散列,它会序列化它。我发现这很方便,因为它允许我写JSON[……]不需要记住我是在解析还是在使用to_json之类的东西。使用它是程序员的第一个优点。


推荐阅读
author-avatar
一个人跳舞飘
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有