code_junkie

jQuery - $.each loop through json code

Nov 12th, 2011
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.88 KB | None | 0 0
  1. Define a stack
  2. Define an array
  3. LOOP on each character in the string
  4. IF the top item of the stack is a single or double quote THEN
  5. LOOP through each character until you find a matching single or double quote, then pop it from the stack.
  6. ELSE
  7. IF "{", push onto the stack
  8. IF "}" THEN
  9. pop a "{" from the stack if it is on top
  10. IF the stack is empty THEN //we just finished a full json object
  11. Throw this json object into an array for later consumption
  12. END IF
  13. END IF
  14. IF single-quote, push onto the stack
  15. IF double-quote, push onto the stack
  16. END IF
  17. END LOOP
  18.  
  19. {"foo": "}{", "bar": 42}
  20.  
  21. <html>
  22. <head>
  23. <script type="text/javascript" src="jquery-1.2.6.js"></script>
  24. <script type="text/javascript">
  25.  
  26. function handleClick() {
  27. var jsonStrs = parse();
  28. var jsonObjs = [];
  29. for(var j=0;j<jsonStrs.length;j++) jsonObjs.push( parseJSON(jsonStrs[j]) );
  30.  
  31. //jsonObjs now contains an array of json objects
  32.  
  33. document.getElementById('log').innerHTML = '';
  34. displayResults(jsonObjs);
  35. }
  36.  
  37. function displayResults(jsonObjs) {
  38. for(var k=0; k<jsonObjs.length; k++) {
  39. ShowObjProperties(jsonObjs[k]);
  40. }
  41. }
  42.  
  43. function ShowObjProperties(obj) {
  44. var property, propCollection = "";
  45.  
  46. for(property in obj) {
  47. propCollection += (property + ": " + obj[property] + "<br>");
  48. }
  49.  
  50. log(propCollection);
  51. }
  52.  
  53.  
  54. function parseJSON(str) {
  55. var x_result = null;
  56. eval('x_result = ' + str);
  57. return x_result;
  58. }
  59.  
  60. function parse() {
  61. //Setup
  62. var out = $('#output');
  63. var rawinput = $('#inputtext').val();
  64. var input = rawinput.split('');
  65. var stack = [];
  66. stack.top = function() {
  67. if (this.length == 0) return null;
  68. return this[this.length-1];
  69. }
  70. var jsonStrs = [];
  71.  
  72. //Main Loop
  73. var ch = '';
  74. var top = '';
  75. var cursor = 0;
  76. var i = 0;
  77. while (i<input.length) {
  78. //Current Character
  79. ch = input[i];
  80.  
  81. top = stack.top();
  82.  
  83. if(top == "'" || top == '"') { //Ignore the rest of the string
  84. //You can add validation for possible unsafe javascript inside a string, here.
  85.  
  86. ch = input[++i];
  87.  
  88. while(ch != top) {
  89. i++;
  90. if(i>=input.length) {
  91. alert('malformed string');
  92. break;
  93. }
  94. ch = input[i];
  95. }
  96. stack.pop();
  97.  
  98. } else {
  99. //You can add validation for unsafe javascript here.
  100.  
  101. if(ch == ' ') {
  102. i++;
  103. continue; // Ignore spaces
  104. }
  105.  
  106. if(ch == "{" || ch == "'" || ch == '"') stack.push(ch);
  107. if(ch == "}") {
  108. if(top=="{") {
  109. stack.pop();
  110. } else {
  111. alert('malformed string');
  112. break;
  113. }
  114.  
  115. if(stack.length == 0) {
  116. var str = rawinput.substring(cursor, i+1)
  117. jsonStrs.push(str);
  118. cursor = i+1;
  119. }
  120. }
  121. }
  122.  
  123. i++;
  124. }
  125.  
  126. return jsonStrs;
  127. }
  128.  
  129. function log(msg) {
  130. document.getElementById('log').innerHTML += msg + '<br>';
  131. }
  132.  
  133. </script>
  134. </head>
  135.  
  136. <body>
  137. <textarea id="inputtext" rows="5" cols="40" style="overflow:auto">{foo:'bar'}</textarea><br>
  138. <button id="btnParse" onclick="handleClick();">Parse!</button><br /><br />
  139.  
  140. <div id="output">
  141. </div>
  142.  
  143. <b>Results:</b>
  144. <div id="log"></div>
  145.  
  146. </body>
  147. </html>
  148.  
  149. var jsonWrong = '{a:1}{a:2}{a:3}';
  150. var jsonRight = jsonWrong.replace('}{', '},{');
  151. var json = eval('('+jsonRight+')');
  152.  
  153. [
  154. {JSON},
  155. {JSON},
  156. {JSON},
  157. {JSON}
  158. ]
  159.  
  160. var string = "{"key":"val}{ue"}{'key':'val}{ue'}{ "asdf" : 500 }";
  161. var result = string.match(/('.*?')|(".*?")|(d+)|({)|(:)|(})/g);
  162. var newstring = "";
  163. for (var i in result) {
  164. var next = parseInt(i) + 1;
  165. if (next <= result.length) {
  166. if (result[i] == "}" && result[next] == "{") {
  167. newstring += "},";
  168. }
  169. else {
  170. newstring += result[i];
  171. }
  172. }
  173.  
  174. $.each(eval(newstring), function() {
  175. //code that uses the JSON values
  176. alert(this.value1);
  177. alert(this.value2);
  178. });
Add Comment
Please, Sign In to add comment