function test_json_parse(){
var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';
var contact = JSON.parse(jsontext);
document.write(contact.surname + ", " + contact.firstname + ", "+ contact.phone);
}
Aaberg, Jesper, 555-0100,555-0120
nodejs 中用JSON.parse(),提示undefined:1 [object object] Unexpected token 0
@jiyinyiyong 正解我觉得应该是这样的,JSON.parse(string)
采用了严格认证模式,参数string必须是一个符合JSON标准的字符串,例如标准中提到:键必须是字符串,字符串必须是双引号,只能出现字符串、数字、布尔这三种基本数据类型或者以这三种基本数据类型为元素的数组[]或者对象{}。对于程序中使用JSON.parse进行转换时,还约束了string中最好不要在2个键值对间有其他的符号例如空格、制表符、换行等。虽然有些工具会通过自动格式化认为你这个json是标准json字符串,但是建议程序中的json字符串不要违反JSON的一些基本标准。实现这一标准并不是强制的,但是实现标准能让json在其他语言环境下达到通用共识。 所以,出现这个问题,我觉得是直接拿这一长条的字符串(带有换汗和制表符)去转而导致的错误。
很easy的
“article_id”: 59276,
像上面这样的。必须转化成 “article_id”: “59276”,
也就是当你使用JSON.parse()时,key与value必须都得用 双引号 引起来,单引号也不行,必须是双引号,你可以用替换的方法把 冒号 到 豆号之间的加上 双引号
我这里也遇到同样的问题: 读取 xxx.txt(里面就是一段 json)-> JSON.parse( fs.readFileSync( xxx.txt ) ) -> 报 SyntaxError: unexpected token 原因:文件编码问题 (windows 平台)xxx.txt 是用右键新建的文件,然后另存为 ‘utf-8’ 格式,但还是报语法错误 解决:用 sublime text (notepad 之类的也行)重新新建一个并保存,然后就可以成功 parse 了
ItJSON.stringify
not JSON.Stringfy
.
Pro tip - Next time you see a error message on the lines of xyz is not a function
try googling that function name.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
The JSON.parse()
Syntax
JSON.parse(text[, reviver])
Parameters
text
The string to parse as JSON. See the JSON object for a description of JSON syntax.
reviver
Optional
If a function, prescribes how the value originally produced by parsing is transformed, before being returned.
Returns
Returns the Object corresponding to the given JSON text
.
Throws
Throws a SyntaxError exception if the string to parse is not valid JSON.
Examples
Using JSON.parse()
JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null
Using the reviver
parameter
If a reviver
is specified, the value computed by parsing is transformed before being returned. Specifically, the computed value, and all its properties (beginning with the most nested properties and proceeding to the original value itself), are individually run through the reviver
, which is called with the object containing the property being processed as this
and with the property name as a string and the property value as arguments. If the reviver
function returns undefined (or returns no value, e.g. if execution falls off the end of the function), the property is deleted from the object. Otherwise the property is redefined to be the return value.
The reviver
is ultimately called with the empty string and the topmost value to permit transformation of the topmost value. Be certain to handle this case properly, usually by returning the provided value, orJSON.parse()
will return undefined.
JSON.parse('{"p": 5}', function(k, v) {
if (k === '') { return v; } // if topmost value, return it,
return v * 2; // else return v * 2.
}); // { p: 10 }
JSON.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', function(k, v) {
console.log(k); // log the current property name, the last is "".
return v; // return the unchanged property value.
});
// 1
// 2
// 4
// 6
// 5
// 3
// ""
JSON.parse()
does not allow trailing commas
throw a SyntaxError
Specifications
Specification | Status | Comment |
ECMAScript 5.1 (ECMA-262) | Standard | Initial definition. Implemented in JavaScript 1.7. |
ECMAScript 2015 (6th Edition, ECMA-262) | Standard | |
ECMAScript 2016 Draft (7th Edition, ECMA-262) | Draft | |
Browser compatibility
- Desktop
- Mobile
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
Basic support | (Yes) | 3.5 (1.9.1) | 8.0 | 10.5 | 4.0 |
Gecko-specific notes
Starting Gecko 29 (Firefox 29 / Thunderbird 29 / SeaMonkey 2.26), a malformed JSON string yields a more detailed error message containing the line and column number that caused the parsing error. This is useful when debugging large JSON data.
JSON.parse('[1, 2, 3, 4,]');
// SyntaxError: JSON.parse: unexpected character at
// line 1 column 13 of the JSON data
See also
The JSON.stringify()
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 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
A 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's larger than that. 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.
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.
- Boolean, Number, 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).
- 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]'
// 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'sthis
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 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) {
if (typeof value === "string") {
return undefined;
}
return value;
}
var foo = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7};
var jsonString = JSON.stringify(foo, replacer);
The resulting JSON string is {"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
// }'
toJSON()
behavior
If an object being stringified has a property named toJSON
whose value is a function, then the toJSON()
method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON()
method when called will be serialized. For example:
var obj = {
foo: 'foo',
toJSON: function() {
return 'bar';
}
};
JSON.stringify(obj); // '"bar"'
JSON.stringify({ x: obj }); // '{"x":"bar"}'
Example of using JSON.stringify()
with localStorage
In a case where you want to store an object created by your user and allowing it to be restored even after the browser has been closed, the following example is a model for the applicability ofJSON.stringify()
:
Functions are not a valid JSON data type so they will not work. However, they can be displayed if first converted to a string (e.g. in the replacer), via the function's toString method. Also, some objects like Date will be a string afterJSON.parse().
// Creating an example of JSON
var session = {
'screens': [],
'state': true
};
session.screens.push({ 'name': 'screenA', 'width': 450, 'height': 250 });
session.screens.push({ 'name': 'screenB', 'width': 650, 'height': 350 });
session.screens.push({ 'name': 'screenC', 'width': 750, 'height': 120 });
session.screens.push({ 'name': 'screenD', 'width': 250, 'height': 60 });
session.screens.push({ 'name': 'screenE', 'width': 390, 'height': 120 });
session.screens.push({ 'name': 'screenF', 'width': 1240, 'height': 650 });
// Converting the JSON string with JSON.stringify()
// then saving with localStorage in the name of session
localStorage.setItem('session', JSON.stringify(session));
// Example of how to transform the String generated through
// JSON.stringify() and saved in localStorage in JSON object again
var restoredSession = JSON.parse(localStorage.getItem('session'));
// Now restoredSession variable contains the object that was saved
// in localStorage
console.log(restoredSession);
Specifications
Specification | Status | Comment |
ECMAScript 5.1 (ECMA-262) | Standard | Initial definition. Implemented in JavaScript 1.7. |
ECMAScript 2015 (6th Edition, ECMA-262) | Standard | |
Draft | |
Browser compatibility
- Desktop
- Mobile
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
Basic support | (Yes) | 3.5 (1.9.1) | 8.0 | 10.5 | 4.0 |
See also
- JSON.parse()