Created
May 22, 2010 13:44
-
-
Save louis-wu/410085 to your computer and use it in GitHub Desktop.
json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#JSON is frequently used to exchange data between JavaScript running in browsers and server-based applications | |
#把hash或array的数据结构转换成字符,并把字符写入文件 | |
>> require 'json' | |
=> true | |
>> data = { :name => 'louis', :address => ['Suzhou', 'China'], :age => 30} | |
=> {:address=>["Suzhou", "China"], :age=>30, :name=>"louis"} | |
>> serialized = data.to_json | |
=> "{"address":["Suzhou","China"],"age":30,"name":"louis"}" | |
>> File.open('data.txt', 'w') do |f| | |
?> f.puts serialized | |
>> end | |
#从文件中读取字符化的数据,并转换为数据结构 | |
require 'json' | |
serialized = File.read("data.txt") | |
data = JSON.parse(serialized) | |
=> {"name"=>"dave", "address"=>["tx", "usa"], "age"=>17} | |
#通过j或jj把其参数转换为JSON格式,并打印到STDOUT | |
>> data = { :name => 'louis', :address => ['Suzhou', 'China'], :age => 30} | |
>> jj data | |
{ | |
"address": [ | |
"Suzhou", | |
"China" | |
], | |
"age": 30, | |
"name": "louis" | |
} | |
>> j data | |
{"address":["Suzhou","China"],"age":30,"name":"louis"} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment