Read json into a Stimulus controller

How do you read a local json into a Stimulus controller. Rails 7.0.4, esbuild.

➜ rails new os-stimulus-mapping --j esbuild --css bootstrap --database postgresql --skip-action-mailer --skip-action-mailbox --skip-action-cable where mapping is Leaflet and OpenLayers.

import jsonFile from .src/switzerland.jsondoes not work. I tried getting from/public` with similar results.

Typical error:

Could not resolve “./src/switzerland.json”
15:32:51 js.1 |
15:32:51 js.1 | app/javascript/controllers/ol_advanced_view_controller.js:12:17:
15:32:51 js.1 | 12 │ import data from ‘./src/switzerland.json’

FWIW, I’m trying to implement Advanced View Positioning in Rails Stimulus. I grabbed the json and created a file to try it out. Using this simpler example since I couldn’t get it working in my app.

Thanks for suggestions.

OP with more recent trials and more information.

➜ rails new os-stimulus-mapping --j esbuild --css bootstrap --database postgresql --skip-action-mailer --skip-action-mailbox --skip-action-cable where mapping is Leaflet and OpenLayers. Rails 7.0.4. Ruby 3.0.2

Trying to read a geojson in Rails. Specifically

/public/switzerland.geojson

Console error:

Started GET "/oladvancedview" for ::1 at 2023-02-02 16:42:44 -0800
Processing by DemoController#oladvancedview as HTML
  Rendering layout layouts/application.html.erb
  Rendering demo/oladvancedview.html.erb within layouts/application
  Rendered demo/oladvancedview.html.erb within layouts/application (Duration: 0.3ms | Allocations: 160)
  Rendered layout layouts/application.html.erb (Duration: 3.0ms | Allocations: 2803)
Completed 200 OK in 4ms (Views: 3.7ms | Allocations: 3039)


Started GET "/Users/gscar/Documents/Ruby/RailsTrials/os-stimulus-mapping/public/switzerland.geojson" for ::1 at 2023-02-02 16:42:44 -0800

ActionController::RoutingError (No route matches [GET] "/Users/gscar/Documents/Ruby/RailsTrials/os-stimulus-mapping/public/switzerland.geojson"):

rails routes

 public_switzerland GET  /public/switzerland(.:format)       public#switzerland {:format=>"json"}

routes.rb get 'public/switzerland', defaults: { format: 'json' }

xx.html.erb <% path = File.join Rails.root, 'public', 'switzerland.geojson' %

Passing with Stimulus

	<div id="avmap"
 		data-controller="ol-advanced-view" 
	 		data-ol-advanced-view-target="avmap" 
	 		data-ol-advanced-view-url-value = "<%= path %>" 
	 		style="height:400px" >
	</div>

No Javascript errors in stimulus controller.

Clueless what is going on. How do I read this file? Thank you for any ideas?