Javascript : expected error - javascript

I am unable to decipher the error message Expected :. It occurs when it attempts to execute the code below. I have a string of characters e.g. "Joe":"HR" being passed to it
var p = {
"\"" + m[0] + "\"" + " : " + "\"" + (m[0] = m[1]) + "\""
};
Additional code
for (var key in p)
{
if (p.hasOwnProperty(key))
{
client = selectedPackage.Elements.AddNew(key, p[key]);
client.Update();
}
}

You're defining an object, but only have a key without value, e.g. you're trying to do:
var p = {
key : value
}
But your code is only
var p = {
key
}
You have a :, but since it's inside a string (" : "), it doesn't count.

{} is an object, so it expects a value for the key:
{
"key": "value"
}
In your case, the key is "\"" + m[0] + "\"" + " : " + "\"" + (m[0] = m[1]) + "\"" (which is actually invalid, the error is a little unclear on this), so you need to specify a value as well.
I suspect you want this (from your string, which looks like JSON):
var p = { };
p[m[0]] = m[1];

You don't create an object with a variable key and value by concatenating the text of a literal. You have to use array-style assignment:
var p = {};
p[m[0]] = m[1];

Related

Convert Javascript string to Dictionary

I'm trying to get Redis data in NodeJS. The Redis data needs to be converted to a dictionary for further processing. I gave it a try but finding difficult as parseFloat on string keeps giving me NaN.
Can anyone please help me to do it the correct way? Variable string has the sample data in below code. Please see the expected results below.
var string = "[ '[Timestamp(\'2018-06-29 15:29:00\'), \'260.20\', \'260.40\', \'260.15\', \'260.30\']' ]";
string = string.replace("[", "");
string = string.replace("]", "");
string = string.replace("[", "");
string = string.replace("]", "");
s1 = string
var array = string.split(",");
var final = "{" + "\"date\"" + ":" + "\"" + array[0] + ",\"Open\"" + ":" + "\"" + array[1].trim() + "\"" + ",\"High\"" + ":" + "\"" + array[2].trim() + "\"" + ",\"Low\"" + ":" + "\"" + array[3].trim() + "\"" + ",\"Close\"" + ":" + "\"" + array[4].trim() + "\"" + "}";
console.log(final);
Expected Result:
{
"date": " Timestamp('2018-06-29 15:29:00')",
"Open": "260.20",
"High": "260.40",
"Low": "260.15",
"Close": "260.30"
}
You have extra apostrophes at both sides of your string which is not needed and while parsing parseFloat("'260.20'")it returns NaN. You could remove them from the array as below:
array = array.map( (str) => str.replace(/'/g, '') );
parseFloat(array[1]); // 260.20
It would probably be a whole lot easier to split the string by single-quotes, then combine into an object:
const string = "[ '[Timestamp(\'2018-06-29 15:29:00\'), \'260.20\', \'260.40\', \'260.15\', \'260.30\']' ]";
const [,,timestamp,,Open,,High,,Low,,Close] = string.split("'");
const obj = {
date: `Timestamp('${timestamp}')`,
Open,
High,
Low,
Close
}
console.log(obj);
Note that \' inside a string delimited by double-quotes doesn't do anything - it's the same as '. (If you need a literal backslash, use \\)

How I can print string in javascript

I want to print a string in following manner 'abc',21,'email' in javascript how can I do. below is my code.
var data = [];
data.push('abc');
data.push(21);
data.push('email');
Write a function to quote a string:
function quote(s) {
return typeof s === 'string' ? "'"+s+"'" : s;
}
Now map your array and paste the elements together with a comma:
data . map(quote) . join(',')
Since joining with a comma is the default way to convert an array into a string, you might be able to get away without the join in some situations:
alert (data . map(quote));
since alert converts its parameter into a string. Same with
element.textContent = data . map(quote);
if data is an array defined as
var data = [];
data.push('abc');
data.push(21);
data.push('email');
the use join() method of array to join (concatenate) the values by specifying the separator
try
alert( "'" + data.join("','") + "'" );
or
console.log( "'" + data.join("','") + "'" );
or simply
var value = "'" + data.join("','") + "'" ;
document.body.innerHTML += value;
Now data = ['abc', 21, 'email'];
So we can use forEach function
var myString = '';
data.forEach(function(value, index){
myString += typeof value === 'string' ? "'" + value + "'" : value;
if(index < data.length - 1) myString += ', ';
});
console.log(myString)
Shorter version:
myString = data.map(function(value){
return typeof value === 'string' ? "'" + value + "'" : value;
}).join(', ');
console.log(myString);
JSFiddle: https://jsfiddle.net/LeoAref/ea5fa3de/

Javascript regex replace yields unexpected result

I have this strange issue, hope that someone will explain what is going on.
My intention is to capture the textual part (a-z, hyphen, underscore) and append the numeric values of id and v to it, underscore separated.
My code:
var str_1 = 'foo1_2';
var str_2 = 'foo-bar1_2';
var str_3 = 'foo_baz1_2';
var id = 3;
var v = 2;
str_1 = str_1.replace(/([a-z_-]+)\d+/,'$1' + id + '_' + v);
str_2 = str_2.replace(/([a-z_-]+)\d+/,'$1' + id + '_' + v);
str_3 = str_3.replace(/([a-z_-]+)\d+/,'$1' + id + '_' + v);
$('#test').html(str_1 + '<br>' + str_2 + '<br>' + str_3 + '<br>');
Expected result:
foo3_2
foo-bar3_2
foo_baz3_2
Actual Result:
foo3_2_2
foo-bar3_2_2
foo_baz3_2_2
Any ideas?
JS Fiddle example
Your pattern:
/([a-z_-]+)\d+/
matches only "foo1" in "foo1_2", and "foo" will be the value of the captured group. The .replace() function replaces the portion of the source string that was actually matched, leaving the remainder alone. Thus "foo1" is replaced by "foo3_2", but the original trailing "_2" is still there as well.
If you want to alter the entire string, then your regular expression will have to account for everything in the source strings.
Just try with:
str_1 = str_1.match(/([a-z_-]+)\d+/)[1] + id + '_' + v;
Use this instead to capture 1_2 completely:
str_1 = str_1.replace(/([a-z_-]+)\d+_\d+/,'$1' + id + '_' + v);
Because you want to replace _2 also of string. Solution can be this:
str_1 = str_1.replace(/([a-z_-]+)\d+_\d/,'$1' + id + '_' + v);
str_2 = str_2.replace(/([a-z_-]+)\d+_\d/,'$1' + id + '_' + v);
str_3 = str_3.replace(/([a-z_-]+)\d+_\d/,'$1' + id + '_' + v);
DEMO
Your pattern actually includes the first digits, but it will store only the textual part into $1:
foo1_2
([a-z_-]+)\d+ = foo1
$1 = foo
The pattern stops searching at the first digits of the string.
if you want to replace any characters after the textual part, you could use this pattern:
/([a-z_-]+)\d+.*/

WEIRD: Javascript string.split() and forloop split prepends mysterious comma ',' to resulting string

So I am messing around with JS Objects, trying stuff out. I am taking a GET request, was JSON, now object. I selec the .api path. I want to traverse the object and store it's name so I can pull more JSON for a ORM expirement. Doesn't matter really. But here is the JSON:
var fakeRESTResponse = function() {
return {
"swaggerVersion": "1.2",
"apiVersion": "1.0.0",
"apis": [{
"path": "/Users"
}, {
"path": "/Skills"
}, {
"path": "/Resumes"
}],
"info": {}
};
};
function createSubstr(strin, thechar) {
var substr = [];
for (var i = 0; i < strin.length; i++) {
var str = ' ';
if (strin[i] === thechar) {
console.log("found first match" + strin + ' str[i] ' + strin[i] + ' thechar ' + thechar + ' str: ' + str);
i++;
while (strin[i] !== thechar && strin[i] !== ',' && i < strin.length && strin[i] !== '"') {
if (str === ' ') str = strin[i];
else str += strin[i];
console.log(str + " : " + strin[i]);
i++;
}
substr.push(str);
str = ' ';
}
}
console.log('Return substr ' + substr);
return substr;
}
That was returned from the server. After trying .split, as you will see below, I built a manual function and some weird stuff:
http://codepen.io/willbittner/pen/aObVWG
That code pen above shows the .split('/') function returning the weird objects:
expected: ['Users','Skills','Resumes']
.split: [',Users',',Skills',',Resumes']
Now, if I move the function:
substr.push(str);
str = ' ';
out to the next scope,
**
http://codepen.io/willbittner/pen/GJROEV
**
You get both the for loop and the .split() producing that whack comma.
So I know it has something to do (likely) with the values in the loop changing before they are accessed because I am overlooking something, but I just can't figure out what causes this!!
* Note- I don't want to fix it, so plz don't respond with a different way of doing it. I want to know why this happens. *
To me- if there was a character APPENDED on the end, that would be more acceptable, but what bug in my code PREPENDS a string, as well as SHIFTS it! No Characters were lost! It shifted it as well I guess lol.

Get textual (string) version of an object - displaying in the browser for debugging purposes [duplicate]

I'm trying to find a way to "pretty print" a JavaScript data structure in a human-readable form for debugging.
I have a rather big and complicated data structure being stored in JS and I need to write some code to manipulate it. In order to work out what I'm doing and where I'm going wrong, what I really need is to be able to see the data structure in its entirety, and update it whenever I make changes through the UI.
All of this stuff I can handle myself, apart from finding a nice way to dump a JavaScript data structure to a human-readable string. JSON would do, but it really needs to be nicely formatted and indented. I'd usually use Firebug's excellent DOM dumping stuff for this, but I really need to be able to see the entire structure at once, which doesn't seem to be possible in Firebug.
Use Crockford's JSON.stringify like this:
var myArray = ['e', {pluribus: 'unum'}];
var text = JSON.stringify(myArray, null, '\t'); //you can specify a number instead of '\t' and that many spaces will be used for indentation...
Variable text would look like this:
[
"e",
{
"pluribus": "unum"
}
]
By the way, this requires nothing more than that JS file - it will work with any library, etc.
I wrote a function to dump a JS object in a readable form, although the output isn't indented, but it shouldn't be too hard to add that: I made this function from one I made for Lua (which is much more complex) which handled this indentation issue.
Here is the "simple" version:
function DumpObject(obj)
{
var od = new Object;
var result = "";
var len = 0;
for (var property in obj)
{
var value = obj[property];
if (typeof value == 'string')
value = "'" + value + "'";
else if (typeof value == 'object')
{
if (value instanceof Array)
{
value = "[ " + value + " ]";
}
else
{
var ood = DumpObject(value);
value = "{ " + ood.dump + " }";
}
}
result += "'" + property + "' : " + value + ", ";
len++;
}
od.dump = result.replace(/, $/, "");
od.len = len;
return od;
}
I will look at improving it a bit.
Note 1: To use it, do od = DumpObject(something) and use od.dump. Convoluted because I wanted the len value too (number of items) for another purpose. It is trivial to make the function return only the string.
Note 2: it doesn't handle loops in references.
EDIT
I made the indented version.
function DumpObjectIndented(obj, indent)
{
var result = "";
if (indent == null) indent = "";
for (var property in obj)
{
var value = obj[property];
if (typeof value == 'string')
value = "'" + value + "'";
else if (typeof value == 'object')
{
if (value instanceof Array)
{
// Just let JS convert the Array to a string!
value = "[ " + value + " ]";
}
else
{
// Recursive dump
// (replace " " by "\t" or something else if you prefer)
var od = DumpObjectIndented(value, indent + " ");
// If you like { on the same line as the key
//value = "{\n" + od + "\n" + indent + "}";
// If you prefer { and } to be aligned
value = "\n" + indent + "{\n" + od + "\n" + indent + "}";
}
}
result += indent + "'" + property + "' : " + value + ",\n";
}
return result.replace(/,\n$/, "");
}
Choose your indentation on the line with the recursive call, and you brace style by switching the commented line after this one.
... I see you whipped up your own version, which is good. Visitors will have a choice.
You can use the following
<pre id="dump"></pre>
<script>
var dump = JSON.stringify(sampleJsonObject, null, 4);
$('#dump').html(dump)
</script>
In Firebug, if you just console.debug ("%o", my_object) you can click on it in the console and enter an interactive object explorer. It shows the entire object, and lets you expand nested objects.
For Node.js, use:
util.inspect(object, [options]);
API Documentation
For those looking for an awesome way to see your object, check prettyPrint.js
Creates a table with configurable view options to be printed somewhere on your doc. Better to look than in the console.
var tbl = prettyPrint( myObject, { /* options such as maxDepth, etc. */ });
document.body.appendChild(tbl);
I'm programming in Rhino and I wasn't satisfied with any of the answers that were posted here. So I've written my own pretty printer:
function pp(object, depth, embedded) {
typeof(depth) == "number" || (depth = 0)
typeof(embedded) == "boolean" || (embedded = false)
var newline = false
var spacer = function(depth) { var spaces = ""; for (var i=0;i<depth;i++) { spaces += " "}; return spaces }
var pretty = ""
if ( typeof(object) == "undefined" ) { pretty += "undefined" }
else if ( typeof(object) == "boolean" ||
typeof(object) == "number" ) { pretty += object.toString() }
else if ( typeof(object) == "string" ) { pretty += "\"" + object + "\"" }
else if ( object == null) { pretty += "null" }
else if ( object instanceof(Array) ) {
if ( object.length > 0 ) {
if (embedded) { newline = true }
var content = ""
for each (var item in object) { content += pp(item, depth+1) + ",\n" + spacer(depth+1) }
content = content.replace(/,\n\s*$/, "").replace(/^\s*/,"")
pretty += "[ " + content + "\n" + spacer(depth) + "]"
} else { pretty += "[]" }
}
else if (typeof(object) == "object") {
if ( Object.keys(object).length > 0 ){
if (embedded) { newline = true }
var content = ""
for (var key in object) {
content += spacer(depth + 1) + key.toString() + ": " + pp(object[key], depth+2, true) + ",\n"
}
content = content.replace(/,\n\s*$/, "").replace(/^\s*/,"")
pretty += "{ " + content + "\n" + spacer(depth) + "}"
} else { pretty += "{}"}
}
else { pretty += object.toString() }
return ((newline ? "\n" + spacer(depth) : "") + pretty)
}
The output looks like this:
js> pp({foo:"bar", baz: 1})
{ foo: "bar",
baz: 1
}
js> var taco
js> pp({foo:"bar", baz: [1,"taco",{"blarg": "moo", "mine": "craft"}, null, taco, {}], bleep: {a:null, b:taco, c: []}})
{ foo: "bar",
baz:
[ 1,
"taco",
{ blarg: "moo",
mine: "craft"
},
null,
undefined,
{}
],
bleep:
{ a: null,
b: undefined,
c: []
}
}
I've also posted it as a Gist here for whatever future changes may be required.
jsDump
jsDump.parse([
window,
document,
{ a : 5, '1' : 'foo' },
/^[ab]+$/g,
new RegExp('x(.*?)z','ig'),
alert,
function fn( x, y, z ){
return x + y;
},
true,
undefined,
null,
new Date(),
document.body,
document.getElementById('links')
])
becomes
[
[Window],
[Document],
{
"1": "foo",
"a": 5
},
/^[ab]+$/g,
/x(.*?)z/gi,
function alert( a ){
[code]
},
function fn( a, b, c ){
[code]
},
true,
undefined,
null,
"Fri Feb 19 2010 00:49:45 GMT+0300 (MSK)",
<body id="body" class="node"></body>,
<div id="links">
]
QUnit (Unit-testing framework used by jQuery) using slightly patched version of jsDump.
JSON.stringify() is not best choice on some cases.
JSON.stringify({f:function(){}}) // "{}"
JSON.stringify(document.body) // TypeError: Converting circular structure to JSON
Taking PhiLho's lead (thanks very much :)), I ended up writing my own as I couldn't quite get his to do what I wanted. It's pretty rough and ready, but it does the job I need. Thank you all for the excellent suggestions.
It's not brilliant code, I know, but for what it's worth, here it is. Someone might find it useful:
// Usage: dump(object)
function dump(object, pad){
var indent = '\t'
if (!pad) pad = ''
var out = ''
if (object.constructor == Array){
out += '[\n'
for (var i=0; i<object.length; i++){
out += pad + indent + dump(object[i], pad + indent) + '\n'
}
out += pad + ']'
}else if (object.constructor == Object){
out += '{\n'
for (var i in object){
out += pad + indent + i + ': ' + dump(object[i], pad + indent) + '\n'
}
out += pad + '}'
}else{
out += object
}
return out
}
For anyone checking this question out in 2021 or post-2021
Check out this Other StackOverflow Answer by hassan
TLDR:
JSON.stringify(data,null,2)
here the third parameter is the tab/spaces
This is really just a comment on Jason Bunting's "Use Crockford's JSON.stringify", but I wasn't able to add a comment to that answer.
As noted in the comments, JSON.stringify doesn't play well with the Prototype (www.prototypejs.org) library. However, it is fairly easy to make them play well together by temporarily removing the Array.prototype.toJSON method that prototype adds, run Crockford's stringify(), then put it back like this:
var temp = Array.prototype.toJSON;
delete Array.prototype.toJSON;
$('result').value += JSON.stringify(profile_base, null, 2);
Array.prototype.toJSON = temp;
I thought J. Buntings response on using JSON.stringify was good as well. A an aside, you can use JSON.stringify via YUIs JSON object if you happen to be using YUI. In my case I needed to dump to HTML so it was easier to just tweak/cut/paste PhiLho response.
function dumpObject(obj, indent)
{
var CR = "<br />", SPC = " ", result = "";
if (indent == null) indent = "";
for (var property in obj)
{
var value = obj[property];
if (typeof value == 'string')
{
value = "'" + value + "'";
}
else if (typeof value == 'object')
{
if (value instanceof Array)
{
// Just let JS convert the Array to a string!
value = "[ " + value + " ]";
}
else
{
var od = dumpObject(value, indent + SPC);
value = CR + indent + "{" + CR + od + CR + indent + "}";
}
}
result += indent + "'" + property + "' : " + value + "," + CR;
}
return result;
}
Lots of people writing code in this thread, with many comments about various gotchas. I liked this solution because it seemed complete and was a single file with no dependencies.
browser
nodejs
It worked "out of the box" and has both node and browser versions (presumably just different wrappers but I didn't dig to confirm).
The library also supports pretty printing XML, SQL and CSS, but I haven't tried those features.
A simple one for printing the elements as strings:
var s = "";
var len = array.length;
var lenMinus1 = len - 1
for (var i = 0; i < len; i++) {
s += array[i];
if(i < lenMinus1) {
s += ", ";
}
}
alert(s);
My NeatJSON library has both Ruby and JavaScript versions. It is freely available under a (permissive) MIT License. You can view an online demo/converter at:
http://phrogz.net/JS/neatjson/neatjson.html
Some features (all optional):
Wrap to a specific width; if an object or array can fit on the line, it is kept on one line.
Align the colons for all keys in an object.
Sort the keys to an object alphabetically.
Format floating point numbers to a specific number of decimals.
When wrapping, use a 'short' version that puts the open/close brackets for arrays and objects on the same line as the first/last value.
Control the whitespace for arrays and objects in a granular manner (inside brackets, before/after colons and commas).
Works in the web browser and as a Node.js module.
flexjson includes a prettyPrint() function that might give you what you want.

Categories

Resources