Import blocks from library based on a list in a json file

Import blocks from library based on a list in a json file

Antonin_JubaultSRF25
Participant Participant
336 Views
3 Replies
Message 1 of 4

Import blocks from library based on a list in a json file

Antonin_JubaultSRF25
Participant
Participant

Hello Team,

 

I receive a json with a list of objects I have in my library.

Let's say 

[{ "block_name" : "block1"},{ "block_name" : "block2"},{ "block_name" : "block3"},...]

 

I want, for each json value, to import the corresponding block into my drawing

I am mostly a JS dev and I am discovering lisp here.

 

I was wondering if somebody have heard of a script doing it I could base my researches on ?

 

Appreciate.

 

AJ

0 Likes
337 Views
3 Replies
Replies (3)
Message 2 of 4

CodeDing
Advisor
Advisor

@Antonin_JubaultSRF25 ,

 

...Given this file:

[
  { "block_name" : "block1"},
  { "block_name" : "block2"},
  { "block_name" : "block3"}
]

 

...This code:

;; Hastily parses JSON to Lisp
;; json - string, as json data
;; returns - list or nil, list of data converted from json
(defun ParseJSON (json / )
  (if (eq 'STR (type json))
    (read (vl-string-translate "[]{}:," "()()  " json))
  );if
);defun

;; Reads file at provided path
;; filePath - string, full path & name of file to read
;; returns - string, of file contents (newlines not preserved)
(defun ReadFile (filePath / f line contents)
  (if (setq filePath (findfile filePath))
    (progn
      (setq f (open filePath "r"))
      (while (setq line (read-line f))
        (setq contents (cons line contents))
      );while
      (close f)
      (apply 'strcat (reverse contents))
    );progn
  ;else
    ;; File not found
  );if
);defun

(defun c:MYBLOCKS ( / filePath json data blockName)
  (setq filePath "c:\\users\\me\\test.json")
  (if (and (setq json (ReadFile filePath))
           (setq data (ParseJSON json)))
    (progn
      (foreach item data
        ;;;(prompt "\nHere is full item: ") (print item)
        (setq blockName (cadr item)) ;;<-- this should retrieve "block1", "block2", etc..
        (prompt (strcat "\nBlock Name: " blockName))
      );foreach
      (prompt "\nMYBLOCKS Complete.")
    );progn
  ;else
    (prompt "\nUnable to find file OR parse Json.")
  );if
  (princ)
);defun

 

...Will return this:

Command: MYBLOCKS
Block Name: block1
Block Name: block2
Block Name: block3
MYBLOCKS Complete.

 

...As far as "inserting" the blocks, that will be on you because I have no idea where these blocks are located lol.

 

Best,

~DD

0 Likes
Message 3 of 4

Antonin_JubaultSRF25
Participant
Participant

Thank you so much for the quick answer ! 

I think I have a lot to learn here ! Haha.

 

I'm gonna work on this and get back to you, thank you DD.

Message 4 of 4

CodeDing
Advisor
Advisor

There's more talk about parsing JSON and better functions to parse over on this post:
https://forums.autodesk.com/t5/visual-lisp-autolisp-and-general/parse-json-with-autolisp-visuallisp/...