Advertisement
Try95th

find object from JavaScript codeString

Dec 30th, 2022 (edited)
388
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.83 KB | None | 0 0
  1. ############## FOR EXCTRACTING AN OBJECT DEFINED INSIDE A STRING CONTAINING JavaScript CODE ##############
  2. ################################################ examples ################################################
  3. # findObj_inJS('x=90; y=50; z=3;', 'z') # returns # 3
  4. # findObj_inJS('x=90; y=50; z=3;', ['x', 'y', 'z']) # returns # {'x': 90, 'y': 50, 'z': 3}
  5. # findObj_inJS('d = {"x": 90, "y": 50, "z": 3}', '"x"') # returns # 90
  6. # findObj_inJS('d = {"x": 90, "y": 50, "z": 3}', ['d']) # returns # {'d': {'x': 90, 'y': 50, 'z': 3}}
  7. ##########################################################################################################
  8.  
  9.  
  10. #!pip install slimit # https://slimit.readthedocs.io/en/latest/
  11. import slimit
  12. from slimit.visitors import nodevisitor
  13.  
  14. import json
  15.  
  16. def findObj_inJS(jsStr, objName, findAll=False, jStrict=True, printErr=False):
  17.     tree = slimit.parser.Parser().parse(jsStr)
  18.     objList = objName if isinstance(objName, list) else [objName]
  19.     toRet = {k: [] for k in objList}
  20.  
  21.     for n in nodevisitor.visit(tree):
  22.         if not objList: break
  23.         for c in (n.children() if hasattr(n, 'children') else [n]):
  24.             if not objList: break
  25.             if not (hasattr(c, 'left') and hasattr(c, 'right')): continue
  26.             cName, cVal = c.left.to_ecma(), c.right.to_ecma()
  27.  
  28.             if cName in objList:
  29.                 try: toRet[cName].append(json.loads(cVal))
  30.                 except Exception as e:
  31.                     if printErr: print(type(e), e)
  32.                     if not jStrict: toRet[cName].append(cVal)
  33.                 if toRet[cName] and not findAll: objList.remove(cName)
  34.    
  35.     for k, v in toRet.items():
  36.         if printErr and not v: print('not found: ', k)
  37.         if not findAll: toRet[k] = v[0] if v else None
  38.     return toRet if isinstance(objName, list) else toRet[objName]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement