Advertisement
sluchaynayakotya

json-like string parser

Sep 22nd, 2021
897
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. a = {"rstatus":0,"stderr":"","stdout":"ctrl_interface=\/var\/run\/wpa_supplicant\nupdate_config=1\nautoscan=exponential:3:60\n\nnetwork={\nssid=\"DCGuest\"\npsk=\"ilikertdc\"\npriority=0\n}\n","truncated":false}
  2.  
  3. a = a.stdout
  4.  
  5. a = a.split ( '\n' ) .filter ( e => e ) .join ( ',' ) .replace ( /\=\{\,/g, '={' ) .replace ( /\,\}/g, '}' )
  6.  
  7. a = parse ( a )
  8.  
  9. a = objectify ( a )
  10.  
  11.  
  12. console.log ( a.network.ssid )
  13. console.log ( a.network.psk )
  14.  
  15.  
  16. function parse ( a ) {
  17.     // a is string
  18.  
  19.     let depth = 0
  20.     let starti = -1
  21.  
  22.     let beautyfied = []
  23.     let raw = ''
  24.  
  25.     for ( let i = 0 ; i < a.length ; ++ i ) {
  26.  
  27.         if ( a[ i ] === '{' ) {
  28.  
  29.             if ( depth === 0 ) {
  30.  
  31.                 starti = i
  32.  
  33.             }
  34.  
  35.             ++ depth
  36.  
  37.         }
  38.  
  39.         else if ( a[ i ] === '}' ) {
  40.  
  41.             -- depth
  42.  
  43.             if ( depth === 0 ) {
  44.  
  45.                 beautyfied = [ ... beautyfied, ... beautyfy ( raw ) ]
  46.                 beautyfied[ beautyfied.length - 1 ][ 1 ] = parse ( a.slice ( starti + 1, i ) )
  47.                 raw = ''
  48.  
  49.             }
  50.  
  51.         }
  52.  
  53.         else {
  54.  
  55.             if ( depth === 0 ) {
  56.  
  57.                 raw += a[ i ]
  58.  
  59.             }
  60.  
  61.         }
  62.  
  63.     }
  64.  
  65.     return [ ... beautyfied, ... beautyfy ( raw ) ] .filter ( e => e.length )
  66.  
  67. }
  68.  
  69.  
  70. function beautyfy ( a ) {
  71.     // a is string
  72.  
  73.     return a .split ( ',' ) .map ( e => e.split ( '=' ) .filter ( e => e ) )
  74.  
  75. }
  76.  
  77.  
  78. function objectify ( a ) {
  79.     // a is string or array
  80.  
  81.     if ( typeof a === 'string' ) return a
  82.  
  83.     const o = {}
  84.  
  85.     for ( let e of a ) {
  86.  
  87.         o[ e[ 0 ] ] = objectify ( e[ 1 ] )
  88.  
  89.     }
  90.  
  91.     return o
  92.  
  93. }
  94.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement