1. 程式人生 > >javascript 物件與字串相互轉換函式 JSON.stringify 和 JSON.parse 的使用

javascript 物件與字串相互轉換函式 JSON.stringify 和 JSON.parse 的使用

JSON.stringify()

The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.

Syntax

JSON.stringify(value[, replacer[, space
]])

Parameters

value
The value to convert to a JSON string.
replacer Optional
A function that alters the behavior of the stringification process, or an array of String and Numberobjects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string.
space Optional
String or Number object that's used to insert white space into the output JSON string for readability purposes. If this is a Number, it indicates the number of space characters to use as white space; this number is capped at 10 (if it is greater, the value is just 10). Values less than 1 indicate that no space should be used. If this is a String
, the string (or the first 10 characters of the string, if it's longer than that) is used as white space. If this parameter is not provided (or is null), no white space is used.

Return value

A JSON string representing the given value.

Description

JSON.stringify() converts a value to JSON notation representing it:

  • Properties of non-array objects are not guaranteed to be stringified in any particular order. Do not rely on ordering of properties within the same object within the stringification.
  • BooleanNumber, and String objects are converted to the corresponding primitive values during stringification, in accord with the traditional conversion semantics.
  • If undefined, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array). JSON.stringify can also just return undefined when passing in "pure" values like JSON.stringify(function(){})or JSON.stringify(undefined).
  • All symbol-keyed properties will be completely ignored, even when using the replacer function.
  • Non-enumerable properties will be ignored
JSON.stringify({});                  // '{}'
JSON.stringify(true);                // 'true'
JSON.stringify('foo');               // '"foo"'
JSON.stringify([1, 'false', false]); // '[1,"false",false]'
JSON.stringify({ x: 5 });            // '{"x":5}'

JSON.stringify(new Date(2006, 0, 2, 15, 4, 5)) 
// '"2006-01-02T15:04:05.000Z"'

JSON.stringify({ x: 5, y: 6 });
// '{"x":5,"y":6}' or '{"y":6,"x":5}'
JSON.stringify([new Number(1), new String('false'), new Boolean(false)]);
// '[1,"false",false]'

JSON.stringify({ x: [10, undefined, function(){}, Symbol('')] }); 
// '{"x":[10,null,null,null]}' 
 
// Symbols:
JSON.stringify({ x: undefined, y: Object, z: Symbol('') });
// '{}'
JSON.stringify({ [Symbol('foo')]: 'foo' });
// '{}'
JSON.stringify({ [Symbol.for('foo')]: 'foo' }, [Symbol.for('foo')]);
// '{}'
JSON.stringify({ [Symbol.for('foo')]: 'foo' }, function(k, v) {
  if (typeof k === 'symbol') {
    return 'a symbol';
  }
});
// '{}'

// Non-enumerable properties:
JSON.stringify( Object.create(null, { x: { value: 'x', enumerable: false }, y: { value: 'y', enumerable: true } }) );
// '{"y":"y"}'

The replacer parameter

The replacer parameter can be either a function or an array. As a function, it takes two parameters, the key and the value being stringified. The object in which the key was found is provided as the replacer's this parameter. Initially it gets called with an empty key representing the object being stringified, and it then gets called for each property on the object or array being stringified. It should return the value that should be added to the JSON string, as follows:

  • If you return a Number, the string corresponding to that number is used as the value for the property when added to the JSON string.
  • If you return a String, that string is used as the property's value when adding it to the JSON string.
  • If you return a Boolean, "true" or "false" is used as the property's value, as appropriate, when adding it to the JSON string.
  • If you return any other object, the object is recursively stringified into the JSON string, calling the replacer function on each property, unless the object is a function, in which case nothing is added to the JSON string.
  • If you return undefined, the property is not included (i.e., filtered out) in the output JSON string.
Note: You cannot use the replacer function to remove values from an array. If you return undefined or a function then null is used instead.

Example with a function

function replacer(key, value) {
  // Filtering out properties
  if (typeof value === 'string') {
    return undefined;
  }
  return value;
}

var foo = {foundation: 'Mozilla', model: 'box', week: 45, transport: 'car', month: 7};
JSON.stringify(foo, replacer);
// '{"week":45,"month":7}'

Example with an array

If replacer is an array, the array's values indicate the names of the properties in the object that should be included in the resulting JSON string.

JSON.stringify(foo, ['week', 'month']);  
// '{"week":45,"month":7}', only keep "week" and "month" properties

The space argument

The space argument may be used to control spacing in the final string. If it is a number, successive levels in the stringification will each be indented by this many space characters (up to 10). If it is a string, successive levels will be indented by this string (or the first ten characters of it).

JSON.stringify({ a: 2 }, null, ' ');
// '{
//  "a": 2
// }'

Using a tab character mimics standard pretty-print appearance:

JSON.stringify({ uno: 1, dos: 2 }, null, '\t');
// returns the string:
// '{
//     "uno": 1,
//     "dos": 2
// }'

java字元陣列字串相互轉換

1.字串轉化為字元陣列 public class Hello { public static void main(String args[]){ Scanner input = new Scanner(System.in); String str="abc";

Java整型字串相互轉換

1如何將字串 String 轉換成整數 int?   A. 有兩個方法:   1). int i = Integer.parseInt([String]); 或   i = Integer.parseInt([String],[int radix]);   2). int i = I

mysql 時間字串相互轉換

select str_to_date('2018-02-23 15:01:51', '%Y-%m-%d %H:%i:%s') date; date_format(date,format):時間轉字串 select date_format(now(), '%Y-%m-%d') str;

DateTime結構體字串相互轉換的程式碼實現

問題描述 自定義一個DateTime結構體,程式碼如下: //定義DateTime結構體 struct DateTime { short year; short month; short

MySql資料庫的時間轉換問題 mysql時間字串相互轉換

轉自 https://www.cnblogs.com/wangyongwen/p/6265126.html   mysql時間與字串相互轉換   時間、字串、時間戳之間的互相轉換很常用,但是幾乎每次使用時候都喜歡去搜索一下用法;本文整理一下三者之間的

關於結構體字串相互轉換驗證

/************************************************************************* > File Name: memtest.c > Author: > Mail: > Crea

C++數值字串相互轉換的那些事(一)字串轉數值(轉載請註明)

以前一門心思搞演算法,這個東西覺得自己寫個函式就能實現的事,但是到了公司後才發現同事寫的程式碼裡面,呼叫各種庫函式、window API、流來實現。什麼都不懂的我表示鴨梨很大,今天翻了翻資料瞭解了下各種方法的使用方法、區別以及適用範圍,寫成了這篇又長又臭又沒條理的東西。 注

mysql時間字串相互轉換

時間、字串、時間戳之間的互相轉換很常用,但是幾乎每次使用時候都喜歡去搜索一下用法;本文整理一下三者之間的 轉換(即:date轉字串、date轉時間戳、字串轉date、字串轉時間戳、時間戳轉date,時間戳轉字串)用法,方便日後學習和查閱; 涉及的函式 時間

python 將圖片字串相互轉換

import base64 image='1.jpg' #將圖片encode為二進位制字串方法一 with open(image,'rb') as f: str=base64.b64encode(f.read()) print(type(str)) #將圖片enc

oracle 時間字串相互轉換

to_char(date,format):時間轉字串select to_char(sysdate,'YYYY"年"MM"月"DD"日"') 時間轉字串 from dual;to_date(str,for

JSON.stringify()JSON.parse()分別是什麽

string gif obj bject 什麽 是什麽 分別是 object 對象 JSON.stringify() 從一個對象中解析出字符串 JSON.stringify({"a":"1","b":"2"}) 結果是:"{"a":"1","b":"2"}" JSON.

你不知道的JSON.stringifyJSON.parse

mar png 遍歷 bool 簡單的 log 之間 表示法 名稱 json是JavaScript 對象表示法(JavaScript Object Notation),是一種簡單的數據格式,類似於XML,其格式為名稱/值對,數據用逗號隔開,名稱必須用雙引號括起來。例如:

JSON.stringify()JSON.parse()分別是什麼

JSON.stringify() 從一個物件中解析出字串JSON.stringify({"a":"1","b":"2"})結果是:"{"a":"1","b":"2"}"JSON.parse()從一個字串中解析出JSON物件var str = '{"a":"1","b":"2"

ajax中JSON.stringify()JSON.parse()方法的使用

我們平時使用ajax向後臺傳遞資料時,通常會傳遞json格式的資料,當然這裡還有其它格式,比如xml、html、script、text、jsonp格式。 json型別的資料包含json物件和json型

JSON.stringifyJSON.parse()是如何使用的?

16px 關於 現在 image 報錯 style 理解 用法 滿足 經常做前後端數據交互的程序員就知道,json的使用是必不可少的,那麽在json中JSON.stringify和JSON.parse()就顯的比較重要了,那麽如何使用它們呢? 1 首先在jsp頁面上構造一

JavaScript物件JSON字串相互轉換

JSON(JavaScript Object Notation) 是JavaScript程式語言的一個子集。正因JSON是JavaScript的一個子集,所以它可清晰的運用於此語言中。 eval函式 JSON文字轉換為物件     為了將JSON文字轉換為物件,可以使