Get key value from a HTML attribute array javascript - javascript

This is the HTML attribute:
data-plugin-options="{'Enabled': true, 'StartAt': 30, 'EndAt': 65}"
How can get the value of the keys by javascript by the key name? Such as 'StartAt' value.

Please see below code. we know that singleQuote will give you an error while parsing JSON. so I replace it with doubleQuote.
$(document).ready(function(){
var d=$("#data").attr('data-plugin-options');
d=d.replace(/'/g, '"');
var parsedData=JSON.parse(d);
console.log(parsedData.StartAt);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id='data' data-plugin-options="{'Enabled': true, 'StartAt': 30, 'EndAt': 65}">Some text...</p>

Data in element are always a string, but you can parse it, no problem.
Here is an example how to do it
const myElement = document.querySelector('p') // here you have element object, you can use other ways to get it
const dataString = myElement.dataset.pluginOptions // here you have string of the data
const formattedDataString = dataString.replace(/'/g, '"') // your JSON is wrongly formatted, this is fix
const dataObject = JSON.parse(formattedDataString) // where you have object of the data
const dataValue = dataObject.Enabled // where you have value by key
Your JSON is also wrongly formatted, it has single quotes where JSON spec requires double quotes. You can replace it, but this can bring additional problems in case that content contains double quotes - it will crash your script. I'd suggest to look at JSON generation and change it to standard if possible.
Hope this helps

Related

JS: Passed JSON-Array loses quotation marks

Basically I'm trying to pass an json-array via onclick to a function
<button
onclick='showAccountOverviewModal("<%= accounts[j].name %>", `<%= accounts[j].bills%>`)'>
Click Me
</button>
But, when I try to parse the string via JSON.parse, I realize, that neither the keys, nor the values have quotation marks. Is there any 'good' way to fix this or do I need to use regular expressions?
Best regards
EDIT
This is the corresponding function:
function showAccountOverviewModal(accountName, accountBills) {
$("#accountModalOverviewTitle").text(accountName);
accountBills = JSON.parse(accountBills);
console.log(accountBills);
accountBills.forEach(bill => {
console.log(bill);
});
}
ill rewrite your code using data-* attribute. you can disregard if you dont want this approach.
html
<button class="showaccountmodal"
data-accountName="<%= accounts[j].name %>
data-bill="<%= accounts[j].bills %>">Click Me</button>
jquery
$(".showaccountmodal").on('click', function() {
var accountname = $(this).data('accountName');
var bill = $(this).data('bill');
console.log(accountname);
console.log(bill);
accountBills.forEach(bill => {
console.log(bill);
});
} );
also here's a reference for storing json object in html Store JSON object in data attribute in HTML jQuery
It looks like you you may be passing a javascript array (already parsed) as opposed to a JSON array (a string representing the array). If so, prior to JSON.parseing it, running
console.log(Array.isArray(accountBills))
should print true. If it is actually JSON, that would print false and running
console.log(typeof accountBills)
would print string.
If it is an array, then you don't need to parse it, and removing the JSON.parse line should make it work as expected.

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!

javascript .replace() does not replace every occurence

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);

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);

adding variable value inside a JSON quote

I am trying to create a javascript object,
var systemName = {"system" : varA};
But I want the object to be in the form `{"system" :"varA"}
with varA having the variable value but inserted inside double quotes.
I have tried {"system" : "'+ varA +'"};
but that did not do the trick. Can you point out what I am doing wrong here? I know its a simple things. But sometimes these small things get us stuck at certain points
Try this instead
var systemName = {};
systemName.system = varA;
(or)
systemName["system"] = varA;
You don't want to do this. You shouldn't do this. If it is a string, the JSON parser will handle it for you. Don't worry about adding quotes to it. There is no reason for you to put quotes around the literal value of the variable. You can put quotes around it at the time of output, if you need to to.
var varA = "Hello";
var systemName = {"system" : varA};
console.log(JSON.stringify(systemName));
// {"system":"Hello"}
http://jsfiddle.net/FWBub/
But, if you must do so:
var varA = '"Hello"';
var systemName = {"system" : varA};
console.log(JSON.stringify(systemName));
{"system":"\"Hello\""}
http://jsfiddle.net/FWBub/1
JSON.stringify(varA) will add JSON quotes around the value.

Categories

Resources