2016-06-16 2 views
0

Я следующую структуру JSON:Сортировка JSON данных в Рубине

{ 
    "name": "MessageEnvelope", 
    "type": "record", 
    "fields": [ 
    { 
     "name": "message", 
     "type": 
     { 
      "name": "Message", 
      "type": "record", 
      "fields": [ 
      .... 
      ] 
     } 
    }, 
    { 
     "name": "pipeline_system", 
     "type": { 
       "type": "enum", 
       "name": "PipelineSystem", 
       "symbols": [ "enterprise", "backscoring", "compliance" ] 
       } 
    }, 
    { 
     "name": "batch_id", 
     "type": [ "null", "string" ] 
    } 
] 
} 

Ищу для сортировки выше JSON-файл, как лучше всего, как это могло быть. Например:

fields : [ 
    { 
     "name": "batch_id", 
     "type": [ "null", "string" ] 
    }, 
    ... 
    ... 
    { 
     "name": "pipeline_system", 
     "type": { 
       "type": "enum", 
       "name": "PipelineSystem", 
       "symbols": [ "backscoring", "compliance", "enterprise" ] 
       } 
    } 

Как он сортирует внутренние массивы, а также хеширует. Я пытаюсь написать следующее:

def sort(collection) 
    if collection.is_a?(Hash) 
    puts "Hash Object...." 
    if(collection["type"]=="record") 
     puts "record found...  Type = #{collection["fields"].class}"; 
     if collection["fields"].is_a?(Array) 
     puts "fields type is array...."   #we can sort fields arrays on the basis of name 
     collection["fields"].sort_by{|arrayCollectionElement| arrayCollectionElement["name"] } 
     arrayCollection = collection["fields"] #this is array of hash...we can sort them on the basis of name..done above in sort by... 
     puts "class = #{arrayCollection.class}" 
     puts "sorted fields: #{arrayCollection}" 
     end 
    end #else it is again a hash 
    end 
    collection 
end 

но он не сортирует массив полей на основе имен.

Цените любую возможную помощь!

ответ

1

Если я правильно понял требование:

json = '...' 

require 'json' 
hash = JSON.parse json 

# ⇓ let’s sort the array of fields inplace 
hash['fields'].sort_by! { |o| o['name'] } 

hash 
#⇒ { 
# "fields" => [ 
# [0] { 
#  "name" => "batch_id", 
#  "type" => [ "null", "string" ] 
# }, 
# [1] { 
#  "name" => "message", 
#  "type" => { 
#  "fields" => [], 
#   "name" => "Message", 
#   "type" => "record" 
#  } 
# }, 
# [2] { 
#  "name" => "pipeline_system", 
#  "type" => { 
#   "name" => "PipelineSystem", 
#  "symbols" => [ "enterprise", "backscoring", "compliance" ], 
#   "type" => "enum" 
#  } 
# } 
# ], 
# "name" => "MessageEnvelope", 
# "type" => "record" 
# } 

Для сортировки всех массивов внутри, можно было бы ввести рекурсивную функцию:

def sort_arrays hash 
    hash.each do |_, v| 
    case v 
    when Array then v.sort! 
    when Hash then sort_arrays v 
    end 
    end 
end 

и вызвать его на самом высоком хэше.

+0

Нельзя сортировать имена, а также массивы внутри хеша. Например, «символы»: [«backscoring», «compliance», «enterprise»] ' – scorix

+0

@scorix получил его, обновил. – mudasobwa

+0

@scorix я мог бы получить массив хэшей также как: ' "тип": [ "нуль", {SOME_HASH}, { SOME_HASH} ] ' в настоящее время , когда массив затем v.sort! будет сортировать только массив строк. –

Смежные вопросы