JSON element detection - javascript

I’ve created a string…
{"atts": [{"name": "wedw"}, {"type": "---"}]}
I pile a bunch of these together in an array based on user input and attach them to another string to complete a JSON object that tests out as valid.
So I end up with a global array called fields with a bunch of these little snippets.
So how do I change the name "weds" with a new name? I’ve tried...
function changefieldname(pos){
var obj = JSON.parse(jsonstring);
var oldname = obj.tracelog.fields[pos].atts[0]["name"];
var newname = document.getElementById("newlogfieldname"+pos).value;
fields[pos].replace(oldname, newname);
//writejson();
}
And a bunch of variations. I know everything is checking out correct interms of the variables pos, oldname, and newname. I also know that fields[pos] returns the string in the array I want to correct but it’s not happy. I also tried converting fields[pos] to a string, but the replace function doesn't work on it. I’m sure there is a good reason.

Why even bother trying to do some kind of replacement? Just assign it a new value:
obj.tracelog.fields[pos].atts[0]["name"] = newname;

Related

How do I access a JSON array in JavaScript

I have a PHP script to which I make an Ajax request, and most of it works okay, but I'm having trouble accessing an array in the data returned to the JavaScript function.
So, the PHP has a bunch of regular variables, and one array. The array, $places, has four elements, which each have three values, as so:
[["z","815","1"],["w","2813","0"],["s","1582","2"],["b","1220","5"]]
A relevant excerpt of the PHP script is:
$encoded_places = json_encode($places); // if I don't do this then I end up with a value of "Array"
$qobject->name = "$name";
$qobject->multi = "$multi";
$qobject->places= "$encoded_places";
$myJSON = json_encode($qobject);
echo $myJSON;
In the JavaScript script (using JQuery), I successfully obtain the data from the Ajax request, and I can access all the data okay, except the $places data.
$.getJSON(url, function(data, status){
var stringified = JSON.stringify(data);
var parsedObj = JSON.parse(stringified);
var x = parsedObj.name; // alert(x); // which works fine
var myArray = new Array();
myArray.push(parsedObj.places);
for(var i = 0; i < myArray.length; i++){
console.log(myArray[i]);
}
... and the console will display what I'm expecting, namely:
[["z","815","1"],["w","2813","0"],["s","1582","2"],["b","1220","5"]]
However, I'm having difficulty accessing these values. For example, supposing I try to access the "815" portion of the first element, with something like: myArray[0][1], all I end up with is "[".
I guess somehow this whole piece of data is just a string, instead of an array, but I'm not familiar enough with JavaScript to quite know how to progress.
If, for example, I do this in the JavaScript script (hoping to see 815, 2813, 1582 and 1220 in the alerts) all I'll see is the single alert with "[". (i.e. it does the loop only once, and selects the character in position 1).
for(var i = 0; i < myArray.length; i++){
console.log(myArray[i]);
alert(myArray[i][1]);
}
I would very much appreciate someone explaining:
(a) how I can access the individual elements and values in JS
(b) how I can loop through them, although presumably once it's an array and not a string then the code above should do this.
Many thanks for any assistance.
Now Resolved:
As noted by #charlietfl, below, using quotes in
$qobject->places= "$encoded_places";
screwed things up, along with using json_encode on $places. However, without removing the quotes nothing worked either way. So, removed quotes and just used json_encode on the entire structure at the end, which now works fine.
So, the original snippet of code, given above, now looks like:
$qobject->name = $name;
$qobject->multi = $multi;
$qobject->places= $places;
$myJSON = json_encode($qobject);
echo $myJSON;
Change
$qobject->places = "$encoded_places";
To
$qobject->places = $places;
And get rid of the $encoded_places = json_encode($places); so that the one call to json_encode serializes the whole structure
Try this:
$.getJSON(url, function(data, status){
var parsedObj = JSON.parse(stringified);
console.table(parsedObj.places);
console.log(parsedObj.places)[0][0];
}
In the posted code's getJSON context, data is already a JSON string. So this line is redundantly stringifying your JSON string:
var stringified = JSON.stringify(data);
stringified is now set to a literal/escaped version of the valid JSON string from the data parameter:
[[\"z\",\"815\",\"1\"],[\"w\",\"2813\",\"0\"],[\"s\",\"1582\",\"2\"],[\"b\",\"1220\",\"5\"]]
When that double-stringified value is passed to JSON.parse for the parsedObj reference, it just becomes the original JSON string again (which looks deceptively correct in an alert box).
Strings are iterable in JavaScript, so the for loop was just going over the string.

Dynamically create a TW object in IBM BPM

I am using IBM BPM 8.6
I have an input string as follows:
"\"RECORD_CONTACT\":\"Maram\" , \"DRUG\":\"Panadol\"
In a script on server side, I want to dynamically create a business object like this:
tw.local.recordContact = Maram;
tw.local.drug = Panadol;
How can I dynamically create the business object?
There are a few problems with your request. The first is that you are not creating a business object, you are creating variables. In IBM BPM the variables have to be declared at design time or you will get an error, so invoking attempting to call something like -
tw.local.myVariable = 'Bob';
Will throw an exception if tw.local.myVariable has not been declared. Base on your other question you asked here (link), I'm going to assume you actually have an ANY variable declared called "return" so that
tw.local.return.myVariable = 'Bob'
will work. Given that I based on Sven's answer I think something like the following will work (you will need to validate)
var str = "\"RECORD_CONTACT\":\"Maram\" , \"DRUG\":\"Panadol\"";
var jsonStr = "{" + str.replace(/\\\"/g,'\"') + "}";
var tempValue = JSON.parse(jsonStr);
var keyArray = Object.keys(tempValue);
var valueArray = Object.values(tempValue);
for(var keyCount=0; keyCount<keyArray.length; keyCount++{
var evalString = "tw.local.return."+keyArray[keyCount]+"="+valueArray[keyCount];
eval(evalString);
}
I'll note that doing this is a very bad idea as it would be very brittle code and that using eval() in this manner opens you up to all sorts of possible exploits. It will also fail badly if the value for one of the keys is not a simple type.
-Andrew Paier
One should know what you are going to do with dynamically created Business Objects (BO) to answer you better. Like a very generic way would be - creating JSON object instead of BO.
But if you want to stick with BO then this is only possible when you know all the BO structure (schema) beforehand during design time.
var str = "\"RECORD_CONTACT\":\"Maram\" , \"DRUG\":\"Panadol\"";
vat objArray = str.split("reg ex to split each object string")
foreach (obj in objArray ){
if(obj.indexOf( "RECORD_CONTACT")!=-1)
tw.local.recordContact = new tw.object.RECORD_CONTACT();
//below goes code get value of each attribute of BPM from string
}
else if(obj.indexOf( "DRUG")!=-1){
//similar code to create BO DRUG
}
Don't forget to create BO before using those :)

Get how many instances of a 'field' are in a text, and append each value with the same 'field' to the same variable

So lets say I have a mailto email in which a checkbox question exists that asks the user to pick the best fruits out of a list of fruits (check all that apply.) They end up with apples, bananas, and pears. The mailto email that they trigger then contains the following (assuming the checkboxes in the question are named bestFruits):
...
bestFruits=apples
bestFruits=bananas
bestFruits=pears
...
So in my javascript file, I have the following line to parse values from the email:
var bestFruits = mail.bodyText.match(/bestFruits=\s*(\S.*\S)\s*/);
So my issue is that this would (presumably) take only one value by the end. What I need, is for the javascript to loop and add each value of bestFruits in the email to the bestFruits var so that each value (apples, bananas, and pears) are all in the bestFruits var.
Is there any way to do this? I tried making a for loop, but I couldn't determine the syntax to loop through the mailto email body and add each instance of bestFruits to the variable.
I'm still extremely new to all this, as I was thrust in recently. If I'm missing something fundamental, I'd appreciate a quick pointing-out. If you require any more info, I'd be happy to try to provide it.
Thanks for reading guys!
You don't need looping. You do need to match all the fruits (as per your example, matching all single words after bestFruits), remove bestFruits= from the matches, join the resulting array and store it in a variable. Like this:
var bestFruits = mail.bodyText.match(/bestFruits=\w+/g)
.map(function(x){return x.split('=')[1]})
.join(',');
What does it do:
Matches all your best fruits.
Takes each bestFruits=abc element and replaces it with abc (i.e., splits with = separator and takes the second part)
Makes the string of your fruits (converts the resulting array to string with , joiner).
You were very close - modified your regex a little bit:
var body = `this=is
an=example
bestFruits=apples
bestFruits=bananas
bestFruits=pears
of=doing
things=ok?
`;
var re = /bestFruits=(.*)/g;
var fruitMatches = body.match(re);
var bestFruits = fruitMatches.map(function(fruitMatch) {
return fruitMatch.split('=')[1];
});
console.log(bestFruits); // ["apples", "bananas", "pears"]
Fiddle

making an array or choice field with a string separated with <br/>

I have a string:
Name1<br/>Name2<br/>Name3
Im looking to get a choice selector or an array with just the Names as values. I know you can get just the text of a string, but I cant figure out a way separate them. This list changes so I cant hard code the names in.
I cannot find any code nor do I have anything yet.
Use the split function:
var text = "Name1<br/>Name2<br/>Name3";
var list = text.split("<br/>");
This is easily accomplished using JavaScript built-in split().
var input_s = "Name1<br />Name2<br />Name3";
var input_r = input_s.split("<br />");

Trying to reduce repetition of javascript using a variable

I am trying to reduce the repetition in my code but not having any luck. I reduced the code down to its simplest functionality to try and get it to work.
The idea is to take the last two letters of an id name, as those letters are the same as a previously declared variable and use it to refer to the old variable.
I used the alert to test whether I was getting the right output and the alert window pops up saying "E1". So I am not really sure why it wont work when I try and use it.
E1 = new Audio('audio/E1.ogg');
$('#noteE1').click(function() {
var fileName = this.id.slice(4);
//alert(fileName); used to test output
fileName.play();
$('#note' + fileName).addClass('active');
});
The code block works when I use the original variable E1 instead of fileName. I want to use fileName because I am hoping to have this function work for multiple elements on click, instead of having it repeated for each element.
How can I make this work? What am I missing?
Thanks.
fileName is still a string. JavaScript does not know that you want to use the variable with the same name. You are calling the play() method on a string, which of course does not exist (hence you get an error).
Suggestion:
Store your objects in a table:
var files = {
E1: new Audio('audio/E1.ogg')
};
$('#noteE1').click(function() {
var fileName = this.id.slice(4);
//alert(fileName); used to test output
files[fileName].play();
$('#note' + fileName).addClass('active');
});
Another suggestion:
Instead of using the ID to hold information about the file, consider using HTML5 data attributes:
<div id="#note" data-filename="E1">Something</div>
Then you can get the name with:
var filename = $('#note').data('filename');
This makes your code more flexible. You are not dependent on giving the elements an ID in a specific format.

Categories