Converting a badly stringfied json to a json object - javascript

I have some data i am pulling from a web service. This is the string
(Body:'3886' MessageProperties [headers={}, timestamp=null,
messageId=null, userId=null, receivedUserId=null, appId=null,
clusterId=null, type=null, correlationId=null,
correlationIdString=null, replyTo=null,
contentType=application/x-java-serialized-object,
contentEncoding=null, contentLength=0, deliveryMode=null,
receivedDeliveryMode=PERSISTENT, expiration=null, priority=0,
redelivered=false, receivedExchange=,
receivedRoutingKey=bottomlesspit, receivedDelay=null, deliveryTag=62,
messageCount=0, consumerTag=amq.ctag-sCwfLaMEqWp2GkFwFrY1yg,
consumerQueue=bottomlesspit])
It looks like json but the key value pairs are almost fine but the most important key which is Body isn't like other keys as the string would tell.
I need to read the value of Body and be able to get the value like this
console.log(d.body);
//This above outputs the string as shown
obj = eval('{' + d.body + '}');
console.log(obj);
var match = "Body";
var val = obj.find( function(item) { return item.key == match } );
console.log(val);
How can i read the value of the key Body?.

Use this regular expression instead of a match Body:
\bBody:'(\d*)'
This will catch the Body number in group 1.

You can write a parser function get string and extract values. A very simple function is here. You can modify it also for all exceptions exist.
var str = `(Body:'3886' MessageProperties [headers={}, timestamp=null, messageId=null, userId=null, receivedUserId=null, appId=null, clusterId=null, type=null, correlationId=null, correlationIdString=null, replyTo=null, contentType=application/x-java-serialized-object, contentEncoding=null, contentLength=0, deliveryMode=null, receivedDeliveryMode=PERSISTENT, expiration=null, priority=0, redelivered=false, receivedExchange=, receivedRoutingKey=bottomlesspit, receivedDelay=null, deliveryTag=62, messageCount=0, consumerTag=amq.ctag-sCwfLaMEqWp2GkFwFrY1yg, consumerQueue=bottomlesspit])`;
function f(inp) {
var index = str.indexOf(inp),
endIndex;
for(var i = index; i < str.length; i ++) {
if(str[i] == ',') {
endIndex = i;
break;
}
}
var output = str.substr(index, endIndex).split('=');
return output;
}
console.log(f('consumerQueue'));

Why not use a regex to match and extract the Body.
Example:
const match = d.body.match(/Body:\'(.+)\'/)
if (match) {
const body = match[1] // This is the value of Body
} else {
// Unable to find Body, handle it here
}

Related

When parsing XML with recursive function, how do I return a string or array from that function?

I've got a working recursive function which goes through an XML doc looking for a matching node name, and then logging matching values...I'm trying to modify it to return a string or an array, and can't figure it out.
This is in Google Apps script. I've tried passing in a blank string into the function, and then returning it at the end, but it doesn't work. Here is the working Logger function:
function logChildren(elements, dataRequired){
for (var i = 0; i < elements.length; i++) {
if (elements[i].getName() == dataRequired){
Logger.log(elements[i].getText());
}
if(elements[i].getContentSize() > 1){
var children = elements[i].getChildren();
logChildren(children, dataRequired);
}
}
};
I tried passing in an empty string, and then returning it like this but it doesn't work:
function logChildren(elements, dataRequired, str){
for (var i = 0; i < elements.length; i++) {
if (elements[i].getName() == dataRequired){
str = str + ", " + elements[i].getText();
}
if(elements[i].getContentSize() > 1){
var children = elements[i].getChildren();
logChildren(children, dataRequired, str);
}
}
return str
};
How do I get a string or array OUT of this function, rather than just console logging it?
Instead of returning str try without it, because str will have all the values. If you return str it might collapse the current iteration. Please let us know whether this worked
Providing your elements is already parsed and valid, this should work.
function logChildren(elements, dataRequired){
values = [];
req = elements.getElementsByTagName(dataRequired);
for (var i = 0; i < req.length; i++) {
values.push(req[i].childNodes[0].nodeValue);
}
return values
};
elements = "<house>" +
"<name>hello</name>" +
"<town>world</town>" +
"<name>cat</name>" +
"<folder>" +
"<name>kitty</name>" +
"</folder>" +
"</house>";
p = new DOMParser();
elements = p.parseFromString(elements, "text/xml");
newValues = logChildren(elements, "name")
console.log(newValues);
I've included my own little xml just to test, and it returns an array.
As you can see, getElementsByTagName even returns values in sub folders.
You should use a global variable or another function, so that the output variable str is outside the scope of the recursed function.
var str = "";//holds all data of recursion
function logChildren(elements, dataRequired){
..
str += ", " + elements[i].getText();
..
}

Test and read variables from file with JS/NodeJS

I am creating a script which is able to read an environment file. The content can be as following:
var1 = 'test'
var2='test2'
var1= 'test'
var3 = 4
I would like to extract the key and the value, eg.:
var1 = 'test' -> result[0]: var1, result[1]: test
How can i write a function that can test if the line read with readFile is valid and afterwards its key (eg. var1) and value (eg. test)? Is it possible to extract both key and value with regexp without running two regexp functions?
Once you have your line stored, you can do something like this:
// line is the line you are processing, object is where you save your stuff
function processLine(line, object) {
var parts = line.split("=");
if (parts.length<2)
return;
// key is parts[0], value is parts[1]
var key = parts.shift();
// if we have equal signs in our value, they will be preserved
var value = parts.join("=");
// get rid of any trailing or preceding spaces
key = key.trim();
value = value.trim();
// is the value a quoted string?
if ((value.charAt(0)==="'" && value.charAt(value.length-1)==="'") ||
(value.charAt(0)==='"' && value.charAt(value.length-1)==='"'))
value = value.slice(1, value.length-1);
// otherwise we assume it's a number
else
value = parseFloat(value);
// TODO: you can check for other stuff here, such as 'true', 'false' and 'null'
// finally, assign it to your object
object[key] = value;
}
Now you just need to call your function for each line, for instance:
var values = {};
for (var i in lines)
processLine(lines[i], values);
Caveats of this approach are numerous. They are easily fixed with some extra code, but I would recommend using something like JSON for defining your configuration values (if that is what they are). There is native support for JSON parsing in javascript, so you could just use that. Maybe you should reconsider your approach.
You can try the following JS code:
function validate(str)
{
var re = /^(\w+)\s*\=\s*(['"]?)(.*?)\2$/;
if ((m = re.exec(str)) !== null) {
return [m[1], m[3]];
}
}
document.getElementById("res").innerHTML =
"Result [0]: " + validate("var1 = 'test'")[0] + "<br>Result [1]: " + validate("var1 = 'test'")[1];
<div id="res"/>
Read the line.. replace quotes with null
//line = "var1 = 'test'";
line = line.replace(/'/g, "");
Split by delimiter =
var result = line.split("=");
//result is an array containing "var1" and "test"
line = "var1 = 'test'";
line = line.replace(/'/g, "");
var result = line.split("=");
document.write("key => "+result[0].trim());
document.write(": value => "+result[1].trim());

How Do I Parse a Pipe-Delimited String into Key-Value Pairs in Javascript

I want to parse the following sort of string into key-value pairs in a Javascript object:
var stringVar = 'PLNC||0|EOR|<br>SUBD|Pines|1|EOR|<br>CITY|Fort Myers|1|EOR|<br>';
Each word of 4 capital letters (PLNC, SUBD, and CITY) is to be a key, while the word(s) in the immediately following pipe are to be the value (the first one, for PLNC, would be undefined, the one for SUBD would be 'Pines', the one for CITY would be 'Fort Myers').
Note that '|EOR|' immediately precedes every key-value pair.
What is the best way of doing this?
I just realised it's technically a csv format with interesting line endings. There are limitations to this in that your variable values cannot contain any | or < br> since they are the tokens which define the structure of the string. You could of course escape them.
var stringVar = 'PLNC||0|EOR|<br>SUBD|Pines|1|EOR|<br>CITY|Fort Myers|1|EOR|<br>';
function decodeString(str, variable_sep, line_endings)
{
var result = [];
var lines = str.split(line_endings);
for (var i=0; i<lines.length; i++) {
var line = lines[i];
var variables = line.split(variable_sep);
if (variables.length > 1) {
result[variables[0]] = variables[1];
}
}
return result;
}
var result = decodeString(stringVar, "|", "<br>");
console.log(result);
If you have underscore (and if you don't, then just try this out by opening up your console on their webpage, because they've got underscore included :)
then play around with it a bit. Here's a start for your journey:
_.compact(stringVar.split(/<br>|EOR|\|/))
Try
function parse(str) {
var str = str.replace(/<br>/gi);
console.log(str);
var arr = str.split('|');
var obj = {};
for (var i=0; i<arr.length; i=i+4) {
var key = arr[i] || '';
var val_1 = arr[i+1] || '';
var val_2 = arr[i+2] || '';
if(key) {
obj[key] = val_1 + ':' + val_2; //or similar
}
}
return obj;
}
DEMO
This will work on the particular data string in the question.
It will also work on other data string of the same general format, but relies on :
<br> being discardable before parsing
every record being a group of 4 string elements delineated by | (pipe)
first element of each record is the key
second and third elements combine to form the value
fourth element is discardable.

How to parse data in javascript using regex?

How can I use regex in javascript to put items and its values in a array ?
This is my data sample:
battery.voltage: 13.50
battery.voltage.nominal: 12.0
beeper.status: enabled
device.type: ups
driver.name: blazer_ser
driver.parameter.pollinterval: 2
Thanks
use the below code to do that... here variable data contains your data...
data=data.split(/\n+/);
var output={};
for(var i=0;i<data.length;i++){
var a=data[i].split(/:\040+/);
output[a[0]]=a[1];
}
These codes will give you an array like below...
Array (
battery.voltage: "13.50",
battery.voltage: "12.0",
beeper.status: "enabled",
device.type: "ups",
driver.name: "blazer_ser",
driver.parameter.pollinterval: "2"
)
Example:
output['driver.name'] === "blazer_ser"
Why use regular expression, you can simply use substr and indexOf. Assuming you have your list stored in an array you can simply loop through the entries and split on the first occurrence of a colon.
var items = [...]; // Your items.
var arr = {};
for (var i = items.length - 1; i >= 0; i--) {
var key = items[i].substr(0, items[i].indexOf(':'));
var value = items[i].substr(items[i].indexOf(':') + 1).trim();
arr[key] = value;
}
This solution will only work in browsers implementing the trim method. If you want to be on the save side you can overwrite the String.prototype and add the trim method. (See Trim string in JavaScript?)
If you have your items as a string separated by newlines you can easily split it into an array through split;
var list = "battery.voltage: 13.50\n"
+ "battery.voltage.nominal: 12.0\n"
+ "beeper.status: enabled\n"
+ "device.type: ups\n"
+ "driver.name: blazer_ser\n"
+ "driver.parameter.pollinterval: 2";​​
var items = list.split(/\n/);
DEMO
Here's a solution that makes only one pass through the string data using a single regex:
var list = "battery.voltage: 13.50\n"
+ "battery.voltage.nominal: 12.0\n"
+ "beeper.status: enabled\n"
+ "device.type: ups\n"
+ "driver.name: blazer_ser\n"
+ "driver.parameter.pollinterval: 2";
function parse(data) {
var match, result = {};
var pattern = /\s*([^:\s]+)\s*:\s*([^:\s]+)$/gm;
while (match = pattern.exec(data)) {
result[match[1]] = match[2];
}
return result;
}
var test = parse(list);
// dump array
for (var i in test)
console.log(i + ": " + test[i]);
// select one
console.log(test["driver.parameter.pollinterval"]);
Click here to try it out on jsfiddle

Get string from url using jQuery?

Say I have http://www.mysite.com/index.php?=332
Is it possible to retrieve the string after ?= using jQuery? I've been looking around Google only to find a lot of Ajax and URL vars information which doesn't seem to give me any idea.
if (url.indexOf("?=") > 0) {
alert('do this');
}
window.location is your friend
Specifically window.location.search
First your query string is not correct, then you can simply take the substring between the indexOf '?=' + 1 and the length of the string. Please see : http://www.w3schools.com/jsref/jsref_substring.asp
When it is easy to do without JQuery, do it with js only.
here is a code snippet (not by me , don't remember the source) for returning a value from a query string by providing a name
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results)
{ return 0; }
return results[1] || 0;
}
var myArgs = window.location.search.slice(1)
var args = myArgs.split("&") // splits on the & if that's what you need
var params = {}
var temp = []
for (var i = 0; i < args.length; i++) {
temp = args[i].split("=")
params[temp[0]] = temp[1]
}
// var url = "http://abc.com?a=b&c=d"
// params now might look like this:
// {
// a: "a",
// c: "d"
// }
What are you trying to do? You very well may be doing it wrong if you're reading the URL.

Categories

Resources