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

初始化,读取并解析 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_dataObject (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_dataObject

提供给业务方的获取 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_jsonObject

读取并解析 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