Class: BB::JsonParser

Inherits:
Object
  • Object
show all
Defined in:
lib/cocoapods-bb-PodAssistant/config/json_parser.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_path) ⇒ JsonParser

Returns a new instance of JsonParser.



7
8
9
10
11
12
13
14
15
# File 'lib/cocoapods-bb-PodAssistant/config/json_parser.rb', line 7

def initialize(file_path)
    begin
    json_str = File.read(file_path)
    @data = JSON.parse(json_str)
    rescue JSON::ParserError => e
    puts "JSON解析失败: #{e.message} file_path:#{file_path} json_str:#{json_str}".red
    @data = {}
    end
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



5
6
7
# File 'lib/cocoapods-bb-PodAssistant/config/json_parser.rb', line 5

def data
  @data
end

Instance Method Details

#get(*keys) ⇒ Object

获取指定 key 的值(支持嵌套)



18
19
20
21
22
23
# File 'lib/cocoapods-bb-PodAssistant/config/json_parser.rb', line 18

def get(*keys)
    keys.reduce(@data) do |current, key|
    return nil unless current.is_a?(Hash) && current.key?(key)
    current[key]
    end
end

#get_json_dataObject

返回内部完整的 JSON 数据(作为 Hash)



31
32
33
# File 'lib/cocoapods-bb-PodAssistant/config/json_parser.rb', line 31

def get_json_data
    @data
end

#set(key, value) ⇒ Object

设置指定 key 的值(仅一级 key)



26
27
28
# File 'lib/cocoapods-bb-PodAssistant/config/json_parser.rb', line 26

def set(key, value)
    @data[key] = value
end

#to_json(pretty: false) ⇒ Object

将内部数据重新转为 JSON 字符串



36
37
38
# File 'lib/cocoapods-bb-PodAssistant/config/json_parser.rb', line 36

def to_json(pretty: false)
    pretty ? JSON.pretty_generate(@data) : @data.to_json
end