json字符串无法解析问题

json字符串无法解析问题

2023年6月24日发(作者:)

json字符串⽆法解析问题function test_json_parse(){var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';var contact = (jsontext);(e + ", " + ame + ", "+ );}

Aaberg, Jesper, 555-0100,555-0120

nodejs 中⽤(),提⽰undefined:1 [object object] Unexpected token 0

正解我觉得应该是这样的,(string)采⽤了严格认证模式,参数string必须是⼀个符合JSON标准的字符串,例如标准中提到:键必须是字符串,字符串必须是双引号,只能出现字符串、数字、布尔这三种基本数据类型或者以这三种基本数据类型为元素的数组[]或者对象{}。对于程序中使⽤进⾏转换时,还约束了string中最好不要在2个键值对间有其他的符号例如空格、制表符、换⾏等。虽然有些⼯具会通过⾃动格式化认为你这个json是标准json字符串,但是建议程序中的json字符串不要违反JSON的⼀些基本标准。实现这⼀标准并不是强制的,但是实现标准能让json在其他语⾔环境下达到通⽤共识。 所以,出现这个问题,我觉得是直接拿这⼀长条的字符串(带有换汗和制表符)去转⽽导致的错误。

很easy的“article_id”: 59276,像上⾯这样的。必须转化成 “article_id”: “59276”,也就是当你使⽤()时,key与value必须都得⽤ 双引号 引起来,单引号也不⾏,必须是双引号,你可以⽤替换的⽅法把 冒号 到⾖号之间的加上 双引号

我这⾥也遇到同样的问题: 读取 (⾥⾯就是⼀段 json)-> ( leSync( ) ) -> 报 SyntaxError: unexpectedtoken 原因:⽂件编码问题 (windows 平台) 是⽤右键新建的⽂件,然后另存为 ‘utf-8’ 格式,但还是报语法错误 解决:⽤ sublimetext (notepad 之类的也⾏)重新新建⼀个并保存,然后就可以成功 parse 了

ify not

tip - Next time you see a error message on the lines of

xyz is not a function try googling that function name.

The

() method parses a string as JSON, optionally transforming the value produced by (text[, reviver])ParameterstextThe string to parse as JSON. See the object for a description of JSON r OptionalIf a function, prescribes how the value originally produced by parsing is transformed, before being sReturns the corresponding to the given JSON

Throws a exception if the string to parse is not valid esUsing

()('{}'); // {}('true'); // ('"foo"'); // "foo"('[1, 5, "false"]'); // [1, 5, "false"]('null'); // nullUsing the

reviver parameterIf a

reviver is specified, the value computed by parsing is transformed before being returned. Specifically, the computed value, and all itsproperties (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 valueas arguments. If the

reviver function returns (or returns no value, e.g. if execution falls off the end of the function), the property is deleted fromthe object. Otherwise the property is redefined to be the return

reviver is ultimately called with the empty string and the topmost value to permit transformation of the topmost value. Be certain tohandle this case properly, usually by returning the provided value, () will return .('{"p": 5}', function(k, v) { if (k === '') { return v; } // if topmost value, return it, return v * 2; // else return v * 2.}); // { p: 10 }('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', function(k, v) { (k); // log the current property name, the last is "". return v; // return the unchanged property value.});// 1// 2// 4// 6// 5// 3

// ""() does not allow trailing commas// both will throw a ('[1, 2, 3, 4, ]');('{"foo" : 1, }');SpecificationsSpecificationStatusStandard

Draft

CommentStandardInitial definition. Implemented in JavaScript r compatibility

FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (1.9.1)8.010.54.0Basic support(Yes)Gecko-specific notesStarting Gecko 29 (Firefox 29 / Thunderbird 29 / SeaMonkey 2.26), a malformed JSON string yields a more detailed error messagecontaining the line and column number that caused the parsing error. This is useful when debugging large JSON ('[1, 2, 3, 4,]');// SyntaxError: : unexpected character at// line 1 column 13 of the JSON dataSee also

The

ify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, oroptionally including only the specified properties if a replacer array is ify(value[, replacer[, space]])ParametersvalueThe value to convert to a JSON er OptionalA function that alters the behavior of the stringification process, or an array of and objects that serve as a whitelist for selecting theproperties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object areincluded in the resulting JSON OptionalA or object that's used to insert white space into the output JSON string for readability purposes. If this is a

Number, it indicates thenumber 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 thatno 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 whitespace. If this parameter is not provided (or is null), no white space is ify() 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 withinthe same object within the stringification., , and objects are converted to the corresponding primitive values during stringification, in accord with the traditional , a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object) or censored to (when itis found in an array).All symbol-keyed properties will be completely ignored, even when using the

replacer -enumerable properties will be ify({}); // '{}'ify(true); // 'true'ify('foo'); // '"foo"'ify([1, 'false', false]); // '[1,"false",false]'ify({ x: 5 }); // '{"x":5}'ify(new Date(2006, 0, 2, 15, 4, 5))

// '"2006-01-02T15:04:05.000Z"'ify({ x: 5, y: 6 });// '{"x":5,"y":6}' or '{"y":6,"x":5}'ify([new Number(1), new String('false'), new Boolean(false)]);// '[1,"false",false]'// Symbols:ify({ x: undefined, y: Object, z: Symbol('') });// '{}'ify({ [Symbol('foo')]: 'foo' });// '{}'ify({ [('foo')]: 'foo' }, [('foo')]);// '{}'ify({ [('foo')]: 'foo' }, function(k, v) { if (typeof k === 'symbol') { return 'a symbol'; }});// '{}'// Non-enumerable properties:ify( (null, { x: { value: 'x', enumerable: false }, y: { value: 'y', enumerable: true } }) );// '{"y":"y"}'The

replacer parameterThe

replacer parameter can be either a function or an array. As a function, it takes two parameters, the key and the value being object in which the key was found is provided as the replacer'sthis parameter. Initially it gets called with an empty key representing theobject being stringified, and it then gets called for each property on the object or array being stringified. It should return the value that shouldbe added to the JSON string, as follows:If you return a , the string corresponding to that number is used as the value for the property when added to the JSON you return a , that string is used as the property's value when adding it to the JSON you return a , "true" or "false" is used as the property's value, as appropriate, when adding it to the JSON you return any other object, the object is recursively stringified into the JSON string, calling thereplacer function on each property,unless the object is a function, in which case nothing is added to the JSON you return

undefined, the property is not included in the output JSON : You cannot use the

replacer function to remove values from an array. If you return

undefined or a function then

null is used e with a functionfunction 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 = ify(foo, replacer);The resulting JSON string is

{"week":45,"month":7}.Example with an arrayIf

replacer is an array, the array's values indicate the names of the properties in the object that should be included in the resultingJSON ify(foo, ['week', 'month']);

// '{"week":45,"month":7}', only keep "week" and "month" propertiesThe

space argumentThe

space argument may be used to control spacing in the final string. If it is a number, successive levels in the stringification will each beindented 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 charactersof it).ify({ a: 2 }, null, ' ');// '{// "a": 2// }'Using a tab character mimics standard pretty-print appearance:ify({ uno: 1, dos: 2 }, null, 't');// returns the string:// '{// "uno": 1,// "dos": 2// }'toJSON() behaviorIf an object being stringified has a property named

toJSON whose value is a function, then the

toJSON()method customizes JSONstringification behavior: instead of the object being serialized, the value returned by the

toJSON() method when called will be serialized. Forexample:var obj = { foo: 'foo', toJSON: function() { return 'bar'; }};ify(obj); // '"bar"'ify({ x: obj }); // '{"x":"bar"}'Example of using

ify() with

localStorageIn 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, thefollowing example is a model for the applicability ify():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 thereplacer), via the function's toString method. Also, some objects like will be a string after.// Creating an example of JSONvar session = { 'screens': [], 'state': true};({ 'name': 'screenA', 'width': 450, 'height': 250 });({ 'name': 'screenB', 'width': 650, 'height': 350 });({ 'name': 'screenC', 'width': 750, 'height': 120 });({ 'name': 'screenD', 'width': 250, 'height': 60 });({ 'name': 'screenE', 'width': 390, 'height': 120 });({ 'name': 'screenF', 'width': 1240, 'height': 650 });// Converting the JSON string with ify()// then saving with localStorage in the name of m('session', ify(session));// Example of how to transform the String generated through

// ify() and saved in localStorage in JSON object againvar restoredSession = (m('session'));// Now restoredSession variable contains the object that was saved// in (restoredSession);SpecificationsSpecificationStatusStandard

Draft

CommentStandardInitial definition. Implemented in JavaScript r compatibility

FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (1.9.1)8.010.54.0Basic support(Yes)See also

发布者:admin,转转请注明出处:http://www.yc00.com/web/1687606889a24146.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信