Get Component Attribute value to json in Ruby On Rails

In Sketchup 2017, how to i generate the selected component values to json using ruby on rails language. After that i have to store the json file in database?

If anyone know, please help me

Thanks,
Siva S

Bonjour!

SketchUp does not use Ruby on Rails (a library for Ruby), but just the language Ruby.

I am not sure what you want to do, can you explain more precisely which values of a component you mean?

# This is demonstration code. For plugins we put it into a module name space etc.
include json

def json_demo
  model = Sketchup.active_model
  # Get the selected components
  components = model.selection.grep(Sketchup::ComponentInstance)

  # Collect some properties (analog for attributes) into a json-like Ruby hash.
  values = {}
  components.each{ |component|
    values[component.name] = component.volume
  }

  # Serialize the Ruby hash data structure into the corresponding JSON.
  json_string = JSON.generate(values)

  # Write the result to a file (or database).
  filepath = UI.savepanel("Save the values…", "/optional/path", "suggested_name.json")
  return if filepath.nil? # User cancelled the save dialog
  File.open(filepath, "w") { |file|
    file.write(json_string)
  }
end

If you want to do more complicated things than this demo, take a look in the documentation.

Hello,

Please see the above sketchup image. I want to save all the Component Atrribute values in database like json.

For example : {“cab_main_10”=>“[{“position”:{“X”:121.351, “Y”:-5.706, “Z”:0.15}}, {“size”:{“LenX”:49.148, “LenY”:55.229, “LenZ”:40}}, {“custom”:{“a100_exposed_material_front”:Blue, “a10_width”:35, “a110_exposed_material_rear”:white}}…]”}

If you have any queries please let us know.

Thanks,
Siva S

See: AttributeDictionary#each_pair

When the JSON library has been required:

require "json"

… Then, …basically:

def get_json_from_dict( obj, dict_name )
  d = obj.attribute_dictionary(dict_name,false)
  return false if d.nil?
  h = {} # create a hash
  d.each_pair {|k,v| h[k]=v }
  "{ #{dict_name} : #{h.to_json} }"
end

Ref: Index of Classes & Methods in json: Ruby Standard Library Documentation (Ruby 2.2.4)

This topic was automatically closed after 91 days. New replies are no longer allowed.