Internet Explorer truncating flashVars containing JSON - string

This only happens in IE.
I'm using swfobject and loading the flash vars as such
var flashVars = {
myVar:'{"url":"http://google.com/", "id":"9999"}',
};
var params = {
allowFullScreen:"true",
wmode:"transparent",
allowScriptAccess:'always'
};
swfobject.embedSWF("mySwf.swf", "mySwf", "512", "318", "10.0.0", "./js/swfobject/expressInstall.swf", flashVars, params);
Everything works perfectly in all browser but IE. I checked myVar and it comes into the swf as { and that's it. I know it's dying at the '. I've tried putting a \ infront, then tried \\ and kept adding one slash until I got to \\\\\\\\. I even inverted all the slashes and tried the same ritual. Nothing.
I can get the string to finally come through, with inverted quotes and using double slashes, but then my JSON parser gets mad about there being slashes in my string.
Here's an example of what works, but of what is invalid JSON:
"{\\'url\\':\\'http://google.com/\\', \\'id\\':\\'9999\\'}"

Yep IE treats flashVars differently to all the other major browsers, I believe you need to make use of the JavaScript encodeURIComponent method which will escape all reserved characters from your String, eg:
// Removing all reserved characters from the flashVar value.
var flashVars = {
myVar: encodeURIComponent('{"url":"http://google.com/", "id":"9999"}'),
};
If you are passing multiple values in the flashVars then you could iterate through them and encode all chars in a single pass:
var flashVars = {
myVar: '{"url":"http://google.com/", "id":"9999"}',
anotherVar: 42
};
// Escape all values contained in the flashVars object.
for (key in flashVars) {
if (flashVars.hasOwnProperty(key)) {
flashVars[key] = encodeURIComponent(flashVars[key]);
}
}
As #dgmdan and #bcmoney suggested, it would probably make your code easier to read if you made use of JSON.stringify - however, you need to bear in mind that IE8 and below do not have a native JSON object, so you will need to include Crockford's JS Library in your HTML page.
// Making use of a JSON library.
var flashVars = {
myVar: encodeURIComponent(JSON.stringify({ url: "http://google.com/", id: "9999"})),
};
Also, it's worth bearing in mind that flashVars are limited to ~64k; so if you are planning to pass a lot of data, it might be better to use an ExternalInterface call to pull them from the JavaScript instead.

Try this to replace your first 3 lines:
var subVars = { url: "http://google.com/", id: "9999" };
var flashVars = { myVar: JSON.stringify(subVars) };

Related

json_agg result from NodeJS application code is different than the same query in pgAdmin [duplicate]

I have this object:
const myObject = {
"a":"a",
"b":{
"c":"c",
"d":{
"e":"e",
"f":{
"g":"g",
"h":{
"i":"i"
}
}
}
}
};
But when I try to show it using console.log(myObject), I receive this output:
{ a: 'a', b: { c: 'c', d: { e: 'e', f: [Object] } } }
How can I get the full object, including the content of property f?
You need to use util.inspect():
const util = require('util')
console.log(util.inspect(myObject, {showHidden: false, depth: null, colors: true}))
// alternative shortcut
console.log(util.inspect(myObject, false, null, true /* enable colors */))
Outputs
{ a: 'a', b: { c: 'c', d: { e: 'e', f: { g: 'g', h: { i: 'i' } } } } }
You can use JSON.stringify, and get some nice indentation as well as perhaps easier to remember syntax.
console.log(JSON.stringify(myObject, null, 4));
{
"a": "a",
"b": {
"c": "c",
"d": {
"e": "e",
"f": {
"g": "g",
"h": {
"i": "i"
}
}
}
}
}
The third argument sets the indentation level, so you can adjust that as desired.
More detail here in JSON stringify MDN docs if needed.
A compilation of the many useful answers from (at least) Node.js v0.10.33 (stable) / v0.11.14 (unstable) presumably through (at least) v7.7.4 (the version current as of the latest update to this answer). Tip of the hat to Rory O'Kane for his help.
tl;dr
To get the desired output for the example in the question, use console.dir():
console.dir(myObject, { depth: null }); // `depth: null` ensures unlimited recursion
Why not util.inspect()? Because it’s already at the heart of diagnostic output: console.log() and console.dir() as well as the Node.js REPL use util.inspect() implicitly. It’s generally not necessary to require('util') and call util.inspect() directly.
Details below.
console.log() (and its alias, console.info()):
If the 1st argument is NOT a format string: util.inspect() is automatically applied to every argument:
o = { one: 1, two: 'deux', foo: function(){} }; console.log(o, [1,2,3]) // -> '{ one: 1, two: 'deux', foo: [Function] } [ 1, 2, 3 ]'
Note that you cannot pass options through util.inspect() in this case, which implies 2 notable limitations:
Structural depth of the output is limited to 2 levels (the default).
Since you cannot change this with console.log(), you must instead use console.dir(): console.dir(myObject, { depth: null } prints with unlimited depth; see below.
You can’t turn syntax coloring on.
If the 1st argument IS a format string (see below): uses util.format() to print the remaining arguments based on the format string (see below); e.g.:
o = { one: 1, two: 'deux', foo: function(){} }; console.log('o as JSON: %j', o) // -> 'o as JSON: {"one":1,"two":"deux"}'
Note:
There is NO placeholder for representing objects util.inspect()-style.
JSON generated with %j is NOT pretty-printed.
console.dir():
Accepts only 1 argument to inspect, and always applies util.inspect() – essentially, a wrapper for util.inspect() without options by default; e.g.:
o = { one: 1, two: 'deux', foo: function(){} }; console.dir(o); // Effectively the same as console.log(o) in this case.
Node.js v0.11.14+: The optional 2nd argument specifies options for util.inspect() – see below; e.g.:
console.dir({ one: 1, two: 'deux'}, { colors: true }); // Node 0.11+: Prints object representation with syntax coloring.
The REPL: implicitly prints any expression's return value with util.inspect() with syntax coloring;
i.e., just typing a variable's name and hitting Enter will print an inspected version of its value; e.g.:
o = { one: 1, two: 'deux', foo: function(){} } // The REPL echoes the object definition with syntax coloring.
util.inspect() automatically pretty-prints object and array representations, but produces multiline output only when needed.
The pretty-printing behavior can be controlled by the compact property in the optional options argument; false uses multi-line output unconditionally, whereas true disables pretty-printing altogether; it can also be set to a number (the default is 3) to control the conditional multi-line behavior – see the docs.
By default, output is wrapped at around 60 characters thanks, Shrey
, regardless of whether the output is sent to a file or a terminal. In practice, since line breaks only happen at property boundaries, you will often end up with shorter lines, but they can also be longer (e.g., with long property values).
In v6.3.0+ you can use the breakLength option to override the 60-character limit; if you set it to Infinity, everything is output on a single line.
If you want more control over pretty-printing, consider using JSON.stringify() with a 3rd argument, but note the following:
Fails with objects that have circular references, such as module in the global context.
Methods (functions) will by design NOT be included.
You can't opt into showing hidden (non-enumerable) properties.
Example call:
JSON.stringify({ one: 1, two: 'deux', three: true}, undefined, 2); // creates a pretty-printed multiline JSON representation indented with 2 spaces
util.inspect() options object (2nd argument):
An optional options object may be passed that alters certain aspects of the formatted string; some of the properties supported are:
See the latest Node.js docs for the current, full list.
showHidden
if true, then the object's non-enumerable properties [those designated not to show up when you use for keys in obj or Object.keys(obj)] will be shown too. Defaults to false.
depth
tells inspect how many times to recurse while formatting the object. This is useful for inspecting large complicated objects. Defaults to 2. To make it recurse indefinitely, pass null.
colors
if true, then the output will be styled with ANSI color codes. Defaults to false. Colors are customizable [… – see link].
customInspect
if false, then custom inspect() functions defined on the objects being inspected won't be called. Defaults to true.
util.format() format-string placeholders (1st argument)
Some of the supported placeholders are:
See the latest Node.js docs for the current, full list.
%s – String.
%d – Number (both integer and float).
%j – JSON.
%% – single percent sign (‘%’). This does not consume an argument.
Another simple method is to convert it to json
console.log('connection : %j', myObject);
Since Node.js 6.4.0, this can be elegantly solved with util.inspect.defaultOptions:
require("util").inspect.defaultOptions.depth = null;
console.log(myObject);
Try this:
console.dir(myObject,{depth:null})
Both of these usages can be applied:
// more compact, and colour can be applied (better for process managers logging)
console.dir(queryArgs, { depth: null, colors: true });
// get a clear list of actual values
console.log(JSON.stringify(queryArgs, undefined, 2));
perhaps console.dir is all you need.
http://nodejs.org/api/console.html#console_console_dir_obj
Uses util.inspect on obj and prints resulting string to stdout.
use util option if you need more control.
A good way to inspect objects is to use node --inspect option with Chrome DevTools for Node.
node.exe --inspect www.js
Open chrome://inspect/#devices in chrome and click Open dedicated DevTools for Node
Now every logged object is available in inspector like regular JS running in chrome.
There is no need to reopen inspector, it connects to node automatically as soon as node starts or restarts. Both --inspect and Chrome DevTools for Node may not be available in older versions of Node and Chrome.
You can also do
console.log(JSON.stringify(myObject, null, 3));
I think this could be useful for you.
const myObject = {
"a":"a",
"b":{
"c":"c",
"d":{
"e":"e",
"f":{
"g":"g",
"h":{
"i":"i"
}
}
}
}
};
console.log(JSON.stringify(myObject, null, '\t'));
As mentioned in this answer:
JSON.stringify's third parameter defines white-space insertion for
pretty-printing. It can be a string or a number (number of spaces).
JSON.stringify()
let myVar = {a: {b: {c: 1}}};
console.log(JSON.stringify( myVar, null, 4 ))
Great for deep inspection of data objects. This approach works on nested arrays and nested objects with arrays.
You can simply add an inspect() method to your object which will override the representation of object in console.log messages
eg:
var myObject = {
"a":"a",
"b":{
"c":"c",
"d":{
"e":"e",
"f":{
"g":"g",
"h":{
"i":"i"
}
}
}
}
};
myObject.inspect = function(){ return JSON.stringify( this, null, ' ' ); }
then, your object will be represented as required in both console.log and node shell
Update:
object.inspect has been deprecated ( https://github.com/nodejs/node/issues/15549). Use myObject[util.inspect.custom] instead:
const util = require('util')
var myObject = {
/* nested properties not shown */
}
myObject[util.inspect.custom] = function(){ return JSON.stringify( this, null, 4 ); }
console.log(util.inspect(myObject))
Use a logger
Don't try to reinvent the wheel
util.inspect(), JSON.stringify() and console.dir() are useful tools for logging an object while playing in the browser console.
If you are serious about Node.js development, you should definitely use a logger. Using it you can add all the logs you want for debugging and monitoring your application. Then just change the logging level of your logger to keep only the production logs visible.
Additionaly they have already solved all the annoying issues related to logging, like: circular objects, formatting, log levels, multiple outputs and performance.
Use a modern logger
pino is a fast and modern logger for Node.js that has sane defaults to handle circular object/references like depthLimit and edgeLimit. It supports child loggers, transports and a pretty printed output.
Moreover, it has 8 default logging levels that you can customize using the customLevels option:
fatal
error
warn
info
debug
trace
silent
Install it
npm install pino
Use it
const logger = require('pino')()
logger.info('hello world')
Configure it
const logger = pino({
depthLimit: 10,
edgeLimit: 200,
customLevels: {
foo: 35
}
});
logger.foo('hi')
A simple trick would be use debug module to add DEBUG_DEPTH=null as environment variable when running the script
Ex.
DEBUG=* DEBUG_DEPTH=null node index.js
In you code
const debug = require('debug');
debug("%O", myObject);
If you're looking for a way to show the hidden items in you array, you got to pass maxArrayLength: Infinity
console.log(util.inspect(value, { maxArrayLength: Infinity }));
The node REPL has a built-in solution for overriding how objects are displayed, see here.
The REPL module internally uses util.inspect(), when printing values.
However, util.inspect delegates the call to the object's inspect()
function, if it has one.
Easiest option:
console.log('%O', myObject);
const myObject = {
"a":"a",
"b":{
"c":"c",
"d":{
"e":"e",
"f":{
"g":"g",
"h":{
"i":"i"
}
}
}
}
};
console.log(JSON.stringify(myObject));
Output:
{"a":"a","b":{"c":"c","d":{"e":"e","f":{"g":"g","h":{"i":"i"}}}}}

Query nested objects mongoose [duplicate]

I have this object:
const myObject = {
"a":"a",
"b":{
"c":"c",
"d":{
"e":"e",
"f":{
"g":"g",
"h":{
"i":"i"
}
}
}
}
};
But when I try to show it using console.log(myObject), I receive this output:
{ a: 'a', b: { c: 'c', d: { e: 'e', f: [Object] } } }
How can I get the full object, including the content of property f?
You need to use util.inspect():
const util = require('util')
console.log(util.inspect(myObject, {showHidden: false, depth: null, colors: true}))
// alternative shortcut
console.log(util.inspect(myObject, false, null, true /* enable colors */))
Outputs
{ a: 'a', b: { c: 'c', d: { e: 'e', f: { g: 'g', h: { i: 'i' } } } } }
You can use JSON.stringify, and get some nice indentation as well as perhaps easier to remember syntax.
console.log(JSON.stringify(myObject, null, 4));
{
"a": "a",
"b": {
"c": "c",
"d": {
"e": "e",
"f": {
"g": "g",
"h": {
"i": "i"
}
}
}
}
}
The third argument sets the indentation level, so you can adjust that as desired.
More detail here in JSON stringify MDN docs if needed.
A compilation of the many useful answers from (at least) Node.js v0.10.33 (stable) / v0.11.14 (unstable) presumably through (at least) v7.7.4 (the version current as of the latest update to this answer). Tip of the hat to Rory O'Kane for his help.
tl;dr
To get the desired output for the example in the question, use console.dir():
console.dir(myObject, { depth: null }); // `depth: null` ensures unlimited recursion
Why not util.inspect()? Because it’s already at the heart of diagnostic output: console.log() and console.dir() as well as the Node.js REPL use util.inspect() implicitly. It’s generally not necessary to require('util') and call util.inspect() directly.
Details below.
console.log() (and its alias, console.info()):
If the 1st argument is NOT a format string: util.inspect() is automatically applied to every argument:
o = { one: 1, two: 'deux', foo: function(){} }; console.log(o, [1,2,3]) // -> '{ one: 1, two: 'deux', foo: [Function] } [ 1, 2, 3 ]'
Note that you cannot pass options through util.inspect() in this case, which implies 2 notable limitations:
Structural depth of the output is limited to 2 levels (the default).
Since you cannot change this with console.log(), you must instead use console.dir(): console.dir(myObject, { depth: null } prints with unlimited depth; see below.
You can’t turn syntax coloring on.
If the 1st argument IS a format string (see below): uses util.format() to print the remaining arguments based on the format string (see below); e.g.:
o = { one: 1, two: 'deux', foo: function(){} }; console.log('o as JSON: %j', o) // -> 'o as JSON: {"one":1,"two":"deux"}'
Note:
There is NO placeholder for representing objects util.inspect()-style.
JSON generated with %j is NOT pretty-printed.
console.dir():
Accepts only 1 argument to inspect, and always applies util.inspect() – essentially, a wrapper for util.inspect() without options by default; e.g.:
o = { one: 1, two: 'deux', foo: function(){} }; console.dir(o); // Effectively the same as console.log(o) in this case.
Node.js v0.11.14+: The optional 2nd argument specifies options for util.inspect() – see below; e.g.:
console.dir({ one: 1, two: 'deux'}, { colors: true }); // Node 0.11+: Prints object representation with syntax coloring.
The REPL: implicitly prints any expression's return value with util.inspect() with syntax coloring;
i.e., just typing a variable's name and hitting Enter will print an inspected version of its value; e.g.:
o = { one: 1, two: 'deux', foo: function(){} } // The REPL echoes the object definition with syntax coloring.
util.inspect() automatically pretty-prints object and array representations, but produces multiline output only when needed.
The pretty-printing behavior can be controlled by the compact property in the optional options argument; false uses multi-line output unconditionally, whereas true disables pretty-printing altogether; it can also be set to a number (the default is 3) to control the conditional multi-line behavior – see the docs.
By default, output is wrapped at around 60 characters thanks, Shrey
, regardless of whether the output is sent to a file or a terminal. In practice, since line breaks only happen at property boundaries, you will often end up with shorter lines, but they can also be longer (e.g., with long property values).
In v6.3.0+ you can use the breakLength option to override the 60-character limit; if you set it to Infinity, everything is output on a single line.
If you want more control over pretty-printing, consider using JSON.stringify() with a 3rd argument, but note the following:
Fails with objects that have circular references, such as module in the global context.
Methods (functions) will by design NOT be included.
You can't opt into showing hidden (non-enumerable) properties.
Example call:
JSON.stringify({ one: 1, two: 'deux', three: true}, undefined, 2); // creates a pretty-printed multiline JSON representation indented with 2 spaces
util.inspect() options object (2nd argument):
An optional options object may be passed that alters certain aspects of the formatted string; some of the properties supported are:
See the latest Node.js docs for the current, full list.
showHidden
if true, then the object's non-enumerable properties [those designated not to show up when you use for keys in obj or Object.keys(obj)] will be shown too. Defaults to false.
depth
tells inspect how many times to recurse while formatting the object. This is useful for inspecting large complicated objects. Defaults to 2. To make it recurse indefinitely, pass null.
colors
if true, then the output will be styled with ANSI color codes. Defaults to false. Colors are customizable [… – see link].
customInspect
if false, then custom inspect() functions defined on the objects being inspected won't be called. Defaults to true.
util.format() format-string placeholders (1st argument)
Some of the supported placeholders are:
See the latest Node.js docs for the current, full list.
%s – String.
%d – Number (both integer and float).
%j – JSON.
%% – single percent sign (‘%’). This does not consume an argument.
Another simple method is to convert it to json
console.log('connection : %j', myObject);
Since Node.js 6.4.0, this can be elegantly solved with util.inspect.defaultOptions:
require("util").inspect.defaultOptions.depth = null;
console.log(myObject);
Try this:
console.dir(myObject,{depth:null})
Both of these usages can be applied:
// more compact, and colour can be applied (better for process managers logging)
console.dir(queryArgs, { depth: null, colors: true });
// get a clear list of actual values
console.log(JSON.stringify(queryArgs, undefined, 2));
perhaps console.dir is all you need.
http://nodejs.org/api/console.html#console_console_dir_obj
Uses util.inspect on obj and prints resulting string to stdout.
use util option if you need more control.
A good way to inspect objects is to use node --inspect option with Chrome DevTools for Node.
node.exe --inspect www.js
Open chrome://inspect/#devices in chrome and click Open dedicated DevTools for Node
Now every logged object is available in inspector like regular JS running in chrome.
There is no need to reopen inspector, it connects to node automatically as soon as node starts or restarts. Both --inspect and Chrome DevTools for Node may not be available in older versions of Node and Chrome.
You can also do
console.log(JSON.stringify(myObject, null, 3));
I think this could be useful for you.
const myObject = {
"a":"a",
"b":{
"c":"c",
"d":{
"e":"e",
"f":{
"g":"g",
"h":{
"i":"i"
}
}
}
}
};
console.log(JSON.stringify(myObject, null, '\t'));
As mentioned in this answer:
JSON.stringify's third parameter defines white-space insertion for
pretty-printing. It can be a string or a number (number of spaces).
JSON.stringify()
let myVar = {a: {b: {c: 1}}};
console.log(JSON.stringify( myVar, null, 4 ))
Great for deep inspection of data objects. This approach works on nested arrays and nested objects with arrays.
You can simply add an inspect() method to your object which will override the representation of object in console.log messages
eg:
var myObject = {
"a":"a",
"b":{
"c":"c",
"d":{
"e":"e",
"f":{
"g":"g",
"h":{
"i":"i"
}
}
}
}
};
myObject.inspect = function(){ return JSON.stringify( this, null, ' ' ); }
then, your object will be represented as required in both console.log and node shell
Update:
object.inspect has been deprecated ( https://github.com/nodejs/node/issues/15549). Use myObject[util.inspect.custom] instead:
const util = require('util')
var myObject = {
/* nested properties not shown */
}
myObject[util.inspect.custom] = function(){ return JSON.stringify( this, null, 4 ); }
console.log(util.inspect(myObject))
Use a logger
Don't try to reinvent the wheel
util.inspect(), JSON.stringify() and console.dir() are useful tools for logging an object while playing in the browser console.
If you are serious about Node.js development, you should definitely use a logger. Using it you can add all the logs you want for debugging and monitoring your application. Then just change the logging level of your logger to keep only the production logs visible.
Additionaly they have already solved all the annoying issues related to logging, like: circular objects, formatting, log levels, multiple outputs and performance.
Use a modern logger
pino is a fast and modern logger for Node.js that has sane defaults to handle circular object/references like depthLimit and edgeLimit. It supports child loggers, transports and a pretty printed output.
Moreover, it has 8 default logging levels that you can customize using the customLevels option:
fatal
error
warn
info
debug
trace
silent
Install it
npm install pino
Use it
const logger = require('pino')()
logger.info('hello world')
Configure it
const logger = pino({
depthLimit: 10,
edgeLimit: 200,
customLevels: {
foo: 35
}
});
logger.foo('hi')
A simple trick would be use debug module to add DEBUG_DEPTH=null as environment variable when running the script
Ex.
DEBUG=* DEBUG_DEPTH=null node index.js
In you code
const debug = require('debug');
debug("%O", myObject);
If you're looking for a way to show the hidden items in you array, you got to pass maxArrayLength: Infinity
console.log(util.inspect(value, { maxArrayLength: Infinity }));
The node REPL has a built-in solution for overriding how objects are displayed, see here.
The REPL module internally uses util.inspect(), when printing values.
However, util.inspect delegates the call to the object's inspect()
function, if it has one.
Easiest option:
console.log('%O', myObject);
const myObject = {
"a":"a",
"b":{
"c":"c",
"d":{
"e":"e",
"f":{
"g":"g",
"h":{
"i":"i"
}
}
}
}
};
console.log(JSON.stringify(myObject));
Output:
{"a":"a","b":{"c":"c","d":{"e":"e","f":{"g":"g","h":{"i":"i"}}}}}

node.js \ sanitize html and also remove tags

how can I tell "sanitize-html" to actually remove the html tags (keep only the content within)? currently if for example I set it to keep the div sections, in the output it writes also the <div>some content</div> - I want only the inside...('some content')
to make it short - I don't want the tags, attributes etc. - only the content of those elements..
var Crawler = require("js-crawler");
var download = require("url-download");
var sanitizeHtml = require('sanitize-html');
var util = require('util');
var fs = require('fs');
new Crawler().configure({depth: 1})
.crawl("http://www.cnn.com", function onSuccess(page) {
var clean = sanitizeHtml(page.body,{
allowedTags: [ 'p', 'em', 'strong','div' ],
});
console.log(clean);
fs.writeFile('sanitized.txt', clean, function (err) {
if (err) throw err;
console.log('It\'s saved! in same location.');
});
console.log(util.inspect(clean, {showHidden: false, depth: null}));
var str = JSON.stringify(clean.toString());
console.log(str);
/*download(page.url, './download')
.on('close', function () {
console.log('One file has been downloaded.');
});*/
});
I'm the author of sanitize-html.
You can set allowedTags to an empty array. sanitize-html does not discard the contents of a disallowed tag, only the tag itself (with the exception of a few tags like "script" and "style" for which this would not make sense). Otherwise it wouldn't be much use for its original intended purpose, which is cleaning up markup copied and pasted from word processors and the like into a rich text editor.
However, if you have markup like:
<div>One</div><div>Two</div>
That will come out as:
OneTwo
To work around that, you can use the textFilter option to ensure the text of a tag is always followed by at least one space:
textFilter: function(text) {
return text + ' ';
}
However, this will also introduce extra spaces in sentences that contain inline tags like "strong" and "em".
So the more I think about it, the best answer for you is probably a completely different npm module:
https://www.npmjs.com/package/html-to-text
It's widely used and much better suited than your use case. sanitize-html is really meant for situations where you want the tags... just not the wrong tags.

Actionscript deserialize Strings into objects

is there a way to deserialize strings to objects in actionscript:
i.e.
var str:String = "{ id: 1, value: ['a', 500] }";
should be made into an appropriate actionscript object.
this is not json, since the keys are not wrapped in quotes.
Ok, for that type of data pattern, there's not a nice way that I know of to do this. going off the assumption you can't affect the data to make it more JSON-like ... here's off the top of my head what I would conceptually try:
var str:String = "{ id:1, value:['a', 500] }";
// strip off the { and } characters since we've nothing nice to do that for us...
var mynewString:String = str.slice(1, str.length - 1);
var stringItems:Array = mynewString.split(",");
var obj:Object = new Object();
for (var i in stringItems)
{
var objProps:Array = stringItems[i].split(":");
// kill off the quotes here
obj[props[0]] = objProps[1].slice(1, objProps[1].length - 1);
if ( obj[props[0]].indexOf('[') == 0 ) {
// remove [ and ] if there
var maybeStrArray:String = obj[props[0]].slice(1, str.length - 1);
// right now assume we're an array based on our inbound data
var strArr:Array = maybeStrArray.split(",");
obj[props[0]] = strArr;
}
}
Something like that or similar to it anyway. Yes, it's crude, and absolutely it could be fashioned in a way that is more flexible (such as move the string to array convert to its own function so I could use it elsewhere). It's just the first thing that conceptually came to mind as an answer.
Try that, tweak around with it and see if it helps.
You can use as3corelib library for JSON deserialization. It's really not worth spending your time on writing own implementation (except you wish so).

Sharepoint > Which characters are *not* allowed in a list?

I've tried looking this up and haven't come up with the answer I'm looking for; I've found what cannot be included in filenames, folder names, and site names... but nothing on actual fields in a list.
I noticed that the percent symbol (%) is one that's not allowed in files/sites/folders. But it also doesn't populate when I try to pro grammatically add the fields to the list. I am doing this by using a small C# application that sends the data via Sharepoint 2010's built-in web services. I can manually enter the character, but it messes up each field in the row if I try it through code.
I've tried some of the escape characters that I've found via Google (_x26), but these don't seem to work either. Has anyone else had an issue with this? If these characters are allowed, how can I escape them when sending the data through a web service call?
Thanks in advance!
Justin
Any characters that aren't allowed when you enter a field name get encoded in the internal name. The format is a little different to what you show - try "_x0026_".
I usually avoid issues with weird internal names by creating the field with no spaces or special characters in the name, then renaming it. When you rename a field, only the display name changes and you keep the simple internal name.
Characters not allowed in SharePoint file name:
~, #, %, & , *, {, }, \, :, <, >, ?, /, |, "
Pasted from http://chrisbarba.com/2011/01/27/sharepoint-filename-special-characters-not-allowed/
Am I saying something weird when I state that there usually is a reason for certain characters not being allowed. I don't know which or why, but there probably is a reason.
Since you control which fields need to be there you can also dictate their (internal) names. I'd say follow best practice and name your fields using Camel case. And because you created them, you can just map the fields to the according fields in your data source.
As a follow on to #Elisa's answer, here's some JavaScript / TypeScript code that helps to prevent users from uploading files into SharePoint with invalid characters in the file name implemented on Nintex forms.
Here's the gist of the JavaScript version (note you'll have to obviously adapt for your own needs since this was designed for Nintex) :
//------------------------------------------------------------------------
//JavaScript Version:
//Code from http://cc.davelozinski.com/tips-techniques/nintex-form-tips-techniques/javascript-typescript-for-nintex-forms-to-validate-file-names
//------------------------------------------------------------------------
function validateAttachmentNames(eventObject) {
var textbox$ = NWF$(this);
var attachrowid = this.id.substring(10, 47);
var fileUploadid = attachrowid;
var index = attachrowid.substring(36);
//console.log('index:' + index);
//console.log('attachrowid:' + attachrowid);
//console.log('fileUploadid:' + fileUploadid);
if (index == '') {
attachrowid += '0';
}
var fileName = NWF.FormFiller.Attachments.TrimWhiteSpaces(textbox$.val().replace(/^.*[\\\/]/, ''));
var match = (new RegExp('[~#%\&{}+\|]|\\.\\.|^\\.|\\.$')).test(fileName);
if (match) {
isValid = false;
setTimeout(function () {
NWF$("tr[id^='attachRow']").each(function () {
var arrParts = (NWF$(this).find(".ms-addnew")[0]).href.split('"');
var fileName = arrParts[5];
var attachRow = arrParts[1];
var fileUpload = arrParts[3];
var match = (new RegExp('[~#%\&{}+\|]|\\.\\.|^\\.|\\.$')).test(fileName);
if (match) {
console.log(fileName);
NWF.FormFiller.Attachments.RemoveLocal(attachRow, fileUpload, fileName);
alert('Invalid file: ' + fileName + ' You cannot attach files with the following characters ~ # % & * { } \ : < > ? / + | \n\nThe file has been removed.');
}
});
}, 500);
}
}

Resources