Class: BB::JsonParser
- Inherits:
-
Object
- Object
- BB::JsonParser
- Defined in:
- lib/cocoapods-bb-PodAssistant/config/json_parser.rb
Instance Attribute Summary collapse
-
#json_data ⇒ Object
readonly
Returns the value of attribute json_data.
Instance Method Summary collapse
-
#get_json_data ⇒ Object
提供给业务方的获取 JSON 数据方法.
-
#initialize(file_path) ⇒ JsonParser
constructor
初始化,读取并解析 JSON 文件.
-
#read_json ⇒ Object
读取并解析 JSON 文件.
-
#traverse_json(data = @json_data, prefix = "", result = {}) ⇒ Object
遍历 JSON 并返回 key-value 结构.
Constructor Details
#initialize(file_path) ⇒ JsonParser
初始化,读取并解析 JSON 文件
8 9 10 11 |
# File 'lib/cocoapods-bb-PodAssistant/config/json_parser.rb', line 8 def initialize(file_path) @file_path = file_path @json_data = read_json end |
Instance Attribute Details
#json_data ⇒ Object (readonly)
Returns the value of attribute json_data.
5 6 7 |
# File 'lib/cocoapods-bb-PodAssistant/config/json_parser.rb', line 5 def json_data @json_data end |
Instance Method Details
#get_json_data ⇒ Object
提供给业务方的获取 JSON 数据方法
48 49 50 51 |
# File 'lib/cocoapods-bb-PodAssistant/config/json_parser.rb', line 48 def get_json_data return {} unless @json_data traverse_json end |
#read_json ⇒ Object
读取并解析 JSON 文件
14 15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/cocoapods-bb-PodAssistant/config/json_parser.rb', line 14 def read_json begin file_content = File.read(@file_path) JSON.parse(file_content) rescue Errno::ENOENT puts "错误:找不到文件 #{@file_path}" nil rescue JSON::ParserError puts "错误:JSON 解析失败,请检查文件格式" nil end end |
#traverse_json(data = @json_data, prefix = "", result = {}) ⇒ Object
遍历 JSON 并返回 key-value 结构
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/cocoapods-bb-PodAssistant/config/json_parser.rb', line 28 def traverse_json(data = @json_data, prefix = "", result = {}) return result unless data case data when Hash data.each do |key, value| traverse_json(value, "#{prefix}#{key}.", result) end when Array data.each_with_index do |value, index| traverse_json(value, "#{prefix}[#{index}].", result) end else result[prefix.chomp('.')] = data end result end |