javascript .replace() does not replace every occurence - javascript

I get the following when retrieving it.
var data = {"distinct_id"%3A "2222222222222"%2C"%24initial_referrer"%3A "%24direct"%2C"%24initial_referring_domain"%3A "%24direct"}
If I check for typeof data I get a String back.
However, when I try to make a proper object out of it by replacing "%3A" with ":" etc the above object does not replace all occurrences but only the first.
data = data.replace(/\%3A/g,":") only replaces the first "%3A".
How can I make a proper object out of this with distinct_id, $initial_referrer as well as we $initial_referring_domain ?

Testing your code proves that your replace usage is actually okay, it indeed replaces all occurrences of %3A:
var data = '{"distinct_id"%3A "2222222222222"%2C"%24initial_referrer"%3A "%24direct"%2C"%24initial_referring_domain"%3A "%24direct"}';
data = data.replace(/\%3A/g, ":");
alert(data);
However, regular expressions is not correct approach here, as you also have other encoded entities. Use decodeURIComponent function instead:
var data = '{"distinct_id"%3A "2222222222222"%2C"%24initial_referrer"%3A "%24direct"%2C"%24initial_referring_domain"%3A "%24direct"}';
data = decodeURIComponent(data);
alert(data);

Related

Creating object from JSON and parsing JSON - different results

I am trying to use JQuery to parse some JSON being sent back from an AJAX call. It appears to be failing to parse, and JSLint also says it's invalid JSON.
However, if I create the object directly, it works and I am able to loop through it - please see below:
var json = {layers:[{layer1:[17,16,15,14,12]}]}
alert(json)// <- This works and output object Object
var somestring = "{layers:[{layer1:[17,16,15,14,12]}]}"
var parsing = JSON.parse(somestring)
alert(parsing) // <- this doesn't and breaks on parse
// The below code will work provided the parsing is commented out
json.layers.forEach(function (outerObj)
{
Object.keys(outerObj).forEach(function (key)
{
outerObj[key].forEach(function (item)
{
alert(item)
});
});
});
I'm struggling to wrap my head around why it won't parse, but appears to work.
Edit
I realise by wrapping quotes around layers and layer1 fixes it, just not sure why it works one way - but not the other.
there is a difference between javascript object and JSON object, all keys of JSON object must be quoted.
var somestring = "{layers:[{layer1:[17,16,15,14,12]}]}"// not a valid json to parse, it is a normal string, you can use JSON.stringify() to make it a valid json identifiable string.
so the correct JSON string will look like
var somestring = '{"layers":[{"layer1":[17,16,15,14,12]}]}';
var parsedJson = JSON.parse(somestring)
If you change sometring to some of the following examples, it will works.
var somestring = '{"layers":[{"layer1":[17,16,15,14,12]}]}'
var somestring = "{\"layers\":[{\"layer1\":[17,16,15,14,12]}]}"
The reason for this is, basically, that's how JSON was specified.
For further examples, take a look at w3schools
Best practice is to use JSON.stringify(Object) on one side, and JSON.parse(String) on the other. This will save you many hours of scratching your head over some niggling detail.
In your example, you could resolve the problem by
var somestring = JSON.stringify(json)
For future reference, however, JSON keys must be quoted, so your somestring should be written as:
var somestring = '{"layers":[{"layer1":[17,16,15,14,12]}]}'
Good luck!

Node.JS - Filename won't accept a variable

doesn't work:
console.log(obj.html_template); // outputs "myfile.html"
var html = fs.readFileSync(JSON.stringify(obj.html_template)); // file not found.
works:
console.log(obj.html_template); // "myfile.html"
var html = fs.readFileSync("myfile.html"); // Works.
I'm going crazy.
> JSON.stringify('myfile.html')
""myfile.html""
Your code is looking for the file "myfile.html" (note the superfluous quotes) in the filesystem. It doesn't exist.
Just look for it without stringification:
var html = fs.readFileSync(obj.html_template);
When you call JSON.stringify, it will convert all the Strings to the JSON format Strings, with surrounding double quotes. Quoting ECMAScript 5.1 Specification for JSON.stringify,
If Type(value) is String, then return the result of calling the abstract operation Quote with argument value.
And the Quote operation, is defined here, which basically surrounds the string with " and takes care of special characters in the String.
So JSON.stringify converts, a string, for example, abcd.txt to "abcd.txt", like this
console.log(JSON.stringify("abcd.txt"));
// "abcd.txt"
which is not equal to abcd.txt.
console.log(JSON.stringify("abcd.txt") == "abcd.txt");
// false
but equal to "abcd.txt".
console.log(JSON.stringify("abcd.txt") == '"abcd.txt"');
// true
So, your program searches for a file named "abcd.txt" instead of abcd.txt. That is why it is not able to find the file and fails.
To fix this problem, just drop the JSON.stringify and pass the string directly, like this
var html = fs.readFileSync(obj.html_template);
why are you using JSON.stringify in the first place? you should be able to just do
var html = fs.readFileSync(obj.html_template);

TypeError : undefined is not a function when calling replace method

I know the code is very little and I'm missing something small.
fiddle : http://jsfiddle.net/0oa9006e/1/
code :
var veri = "+???+Girdiğiniz eposta adresi 'adfadf' geçersiz.-???-";
var a = veri.match(/\+[\?]*\+(.*)*\-[\?]*\-/g);
a = a.replace(/[\+\-\?]*/g , "");
alert(a);
String.match(param) method returns an Array containing all matches. and array in javascript doesn't have .replace method. hence Error. You could try out something like:
a = a.toString().replace(/[\+\-\?]*/g,""); // Array to string converstion
Your match is returning an array, which doesn't have replace. Try:
a = a[0].replace(/[\+\-\?]*/g , "");
var veri = "+???+Girdiğiniz eposta adresi 'adfadf' geçersiz.-???-";
var a = veri.match(/\+[\?]*\+(.*)*\-[\?]*\-/g);
// The variable 'a' is now an array.
// The first step in debugging is to always make sure you have the values
// you think you have.
console.log(a);
// Arrays have no replace method.
// Perhaps you are trying to access a[0]?
// or did you mean to modify `veri`?
a = a.replace(/[\+\-\?]*/g , "");
alert(a);
When veri.match(/\+[\?]*\+(.*)*\-[\?]*\-/g) is executed, your variable a is initialized to a JavaScript Array, which does not have a replace method.
Use a RegEx tool like Regex101 to see how your regular expression matches on the string veri, and then perform the replace operation on the appropriate element of that array.
Here's an example of your regular expression in use: http://regex101.com/r/hG3uI1/1
As you can see, your regular expression matches the entire string held by veri, so you want to perform the replace operation on the first (and only) element returned by match:
a = a[0].replace(/[\+\-\?]*/g , "");

Javascript: working with query string

I'm trying to write a Javascript function to get the query string of the browser and allow a new key/value to be passed to the function. If the key exists, I need to replace the value. Since I've spent the last 3.5 hours on this, I haven't yet gotten around to the replacing part.
So far, I'm using the answer here: How to get the query string by javascript? to get the query string. However, it doesn't appear to work... The URL I was testing with was: http://www.site.com/poo?drwho=tombaker&companion=k9
var assoc = {};
var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
var queryString = location.search.substring(1);
var keyValues = queryString.split('&');
for(var i in keyValues) {
var key = keyValues[i].split('=');
assoc[decode(key[0])] = decode(key[1]);
}
if(assoc["dr"] === undefined ) {
// not found. todo: replace
}
I'd really appricate any help! Is there any simpler way of doing this using JQuery?
Copy and pasted your code here: http://jsfiddle.net/6KcWh/5/, and added a call to JSON.stringify() to examine the contents of assoc. It turns out assoc is not undefined. But, of course assoc.dr is undefined, because there is no querystring argument of dr. There is a querystring argument of drwho. It looks like you were looking for the wrong querystring argument.
You appear to be misusing for...in.
Try converting your for loop to a standard for (i = 0 ; i < keyValues.length; i++) and check out some other answers about what for...in is used for in JavaScript.

How to parse JSON that has inner layers using Javascript?

I can eval simple JSON with javascript.
var json = '{"amount":"50","id":"3"}';
var out = eval("{" + json + "}");
Now I am using JPA with REST and JSON-nized query result would include table name which makes
JSON having inner JSON so simple eval wouldn't work.
{"inventory":{"amount":"50","id":"3"}}
I've looked around the web for solution but can't find my case.
Should I just do string manipulation and extract {"amount":"50","id":"3"} part?
Or is there other way?
Yes, there is another (better) way! Use JSON.parse() to parse your JSON and get your object out:
var obj = JSON.parse(jsonString);
//then, for example...
var amount = obj.inventory.amount;
For older browsers (IE <8 for example) without native JSON support, include json2.js so this above still works.
Even this should work:
var json = '{"inventory":{"amount":"50","id":"3"}}';
var out = eval("{" + json + "}");
alert(out.inventory.amount);
But better to use JSON.parse
Aniway, I think that the proper way to perform a simple eval is to have the json string surrounded with parenthesis, not curly brackets...
var out = eval("(" + json + ")");
Cf. https://github.com/douglascrockford/JSON-js/blob/master/json.js :
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');

Categories

Resources