[Javascript] The JSON.stringify API

JSON (JavaScript Object Notation) is a standard method to serialize JavaScript objects and is commonly used to transfer data from the server to the browser. The browser has a JSON API that allows you to serialize a JavaScript object or array into aJSON string. This API allows you to customize the serialization very specifically as well.

 

复制代码
console.clear()

testValue()
testSpaces()
testFunctionReplacer()
testArrayReplacer()
testSymbolKeyedValues()
testNonEnumerableValue()
testToJSON()

console.log('Tests passed')



// function declarations
function testValue() {
  var input = {
    name: 'Kent C. Dodds',
    username: 'kentcdodds',
  }
  var expected = '{"name":"Kent C. Dodds","username":"kentcdodds"}'
  var result = JSON.stringify(input)
  
  expect(result).toEqual(expected)
}




function testSpaces() {
  var input = {
    name: {
      first: 'Kent',
      middle: 'Christopher',
      last: 'Dodds'
    },
    username: 'kentcdodds',
  }
  var expected = `{
  "name": {
    "first": "Kent",
    "middle": "Christopher",
    "last": "Dodds"
  },
  "username": "kentcdodds"
}`
  var result = JSON.stringify(input, null, 2)
  
  expect(result).toEqual(expected)
}




function testFunctionReplacer() {
  var input = {
    title: 'Gone with the Wind',
    publishDate: new Date('1936-06-10'),
    movieReleaseDate: new Date('1940-01-17'),
  }

  var expected = '{"title":"Gone with the Wind","publishDate":"1936-06-10","movieReleaseDate":"1940-01-17"}'
  
  var result = JSON.stringify(input, replacer)
  
  expect(result).toEqual(expected)
  
  function replacer(key, value) {
    // `this` is bound to the object in which the value was found
    if (this[key] instanceof Date) {
      return value.substring(0, 10)
    }
    return value
  }
}




function testArrayReplacer() {
  var input = [
    {id: 3, title: 'Inside Out', rating: 98, genres: ['Animation', 'Kids & Family']},
    {id: 6, title: 'The Hunger Games', rating: 84, genres: ['    Drama', 'Mystery & Suspense', 'Science Fiction & Fantasy']},
    {id: 13, title: 'Catch Me If You Can', rating: 96, genres: ['Drama', 'Action & Adventure']},
  ]
  var expected = '[{"id":3,"title":"Inside Out"},{"id":6,"title":"The Hunger Games"},{"id":13,"title":"Catch Me If You Can"}]'
  var result = JSON.stringify(input, ['id', 'title'])
  
  expect(result).toEqual(expected)
}





function testSymbolKeyedValues() {
  var input = {foo: 'foo'}
  var barSymbol = Symbol('bar')
  input[barSymbol] = 'bar'
  
  var expected = '{"foo":"foo"}'
  var result = JSON.stringify(input)
  
  expect(result).toEqual(expected)
}




function testNonEnumerableValue() {
  var input = Object.create(null, {
    theAnswer: {
      value: 42,
      enumerable: true
    },
    theQuestion: {
      value: 'Who knows...',
      enumerable: false
    }
  })
  
  var expected = '{"theAnswer":42}'
  var result = JSON.stringify(input)
  
  expect(result).toEqual(expected)
}




function testToJSON() {
  var input = {
    name: {
      first: 'Dave',
      middle: 'James',
      last: 'Smith',
      toJSON: function(key) {
        return {awesomeName: `The Awesome ${this.first} ${this.middle} ${this.last}`}
        console.log(key, this)
      },
    },
    username: 'djsmith42',
  }
  
  var expected = '{"name":{"awesomeName":"The Awesome Dave James Smith"},"username":"djsmith42"}'
  var result = JSON.stringify(input)
  
  expect(result).toEqual(expected)
}
复制代码

 

posted @   Zhentiw  阅读(225)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示