返回介绍

solution / 2600-2699 / 2633.Convert Object to JSON String / README_EN

发布于 2024-06-17 01:03:01 字数 3025 浏览 0 评论 0 收藏 0

2633. Convert Object to JSON String

中文文档

Description

Given a value, return a valid JSON string of that value. The value can be a string, number, array, object, boolean, or null. The returned string should not include extra spaces. The order of keys should be the same as the order returned by Object.keys().

Please solve it without using the built-in JSON.stringify method.

 

Example 1:

Input: object = {"y":1,"x":2}
Output: {"y":1,"x":2}
Explanation: 
Return the JSON representation.
Note that the order of keys should be the same as the order returned by Object.keys().

Example 2:

Input: object = {"a":"str","b":-12,"c":true,"d":null}
Output: {"a":"str","b":-12,"c":true,"d":null}
Explanation:
The primitives of JSON are strings, numbers, booleans, and null.

Example 3:

Input: object = {"key":{"a":1,"b":[{},null,"Hello"]}}
Output: {"key":{"a":1,"b":[{},null,"Hello"]}}
Explanation:
Objects and arrays can include other objects and arrays.

Example 4:

Input: object = true
Output: true
Explanation:
Primitive types are valid inputs.

 

Constraints:

  • value is a valid JSON value
  • 1 <= JSON.stringify(object).length <= 105
  • maxNestingLevel <= 1000
  • all strings contain only alphanumeric characters

Solutions

Solution 1

function jsonStringify(object: any): string {
  if (object === null) {
    return 'null';
  }
  if (typeof object === 'string') {
    return `"${object}"`;
  }
  if (typeof object === 'number' || typeof object === 'boolean') {
    return object.toString();
  }
  if (Array.isArray(object)) {
    return `[${object.map(jsonStringify).join(',')}]`;
  }
  if (typeof object === 'object') {
    return `{${Object.entries(object)
      .map(([key, value]) => `${jsonStringify(key)}:${jsonStringify(value)}`)
      .join(',')}}`;
  }
  return '';
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文