json.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. /*---------------------------------------------------------------------------------------------
  2. * Copyright (c) Microsoft Corporation. All rights reserved.
  3. * Licensed under the MIT License. See License.txt in the project root for license information.
  4. *--------------------------------------------------------------------------------------------*/
  5. export function stringifyObject(obj, indent, stringifyLiteral) {
  6. if (obj !== null && typeof obj === 'object') {
  7. var newIndent = indent + '\t';
  8. if (Array.isArray(obj)) {
  9. if (obj.length === 0) {
  10. return '[]';
  11. }
  12. var result = '[\n';
  13. for (var i = 0; i < obj.length; i++) {
  14. result += newIndent + stringifyObject(obj[i], newIndent, stringifyLiteral);
  15. if (i < obj.length - 1) {
  16. result += ',';
  17. }
  18. result += '\n';
  19. }
  20. result += indent + ']';
  21. return result;
  22. }
  23. else {
  24. var keys = Object.keys(obj);
  25. if (keys.length === 0) {
  26. return '{}';
  27. }
  28. var result = '{\n';
  29. for (var i = 0; i < keys.length; i++) {
  30. var key = keys[i];
  31. result += newIndent + JSON.stringify(key) + ': ' + stringifyObject(obj[key], newIndent, stringifyLiteral);
  32. if (i < keys.length - 1) {
  33. result += ',';
  34. }
  35. result += '\n';
  36. }
  37. result += indent + '}';
  38. return result;
  39. }
  40. }
  41. return stringifyLiteral(obj);
  42. }