Hi I need to parse a JavaScript array that has multiple keys in it. Here is an example of what I need to do. Any help is appreciated.
[
week1{
Meth:100,
Marijuana:122,
pDrugs:12,
},
week2{
Meth:15,
Marijuana:30,
pDrugs:22,
},
]
I need this to be broken into separate arrays based on if it is week1 or week2. Thanks again in advance.
The end needs to be like this.
week1 = ["Meth:100,Marijuana:122,pDrugs12"] etc.
Your JSON has severe improper formatting. If it's already an object (which I'm guessing it isn't -- otherwise, you'd be getting unexpected token errors in your browser console), then change the brackets to braces, remove the trailing commas, and add colons after the object items that don't have them (after week1 and week2).
If what you have is a string (obtained from XHR or similar), you'll have to do all the changes mentioned above, as well as enclosing each object item within quotation marks. It should look like:
{
"week1": {
"Meth":100,
"Marijuana":122,
"pDrugs":12
},
"week2": {
"Meth":15,
"Marijuana":30,
"pDrugs":22
}
}
Whatever you're dealing with that's serving such horribly invalid JSON ought to be taken out back and shot. Be that as it may, this'll require some serious string manipulation. You're going to have to do some thorough massaging with String.replace() and some regular expressions.
After you get the JSON valid, then you can get week1 with JSON.parse and drilling down the resulting object.
function log(what) { document.getElementById('out').value += what + '\n------------------\n'; }
var tree = '[ week1{ Meth:100, Marijuana:122, pDrugs:12, }, week2{ Meth:15, Marijuana:30, pDrugs:22, }, ]';
// string is raw
log(tree);
tree = tree.replace(
'/\r?\n/g', '' // remove line breaks to make further regexps easier
).replace(
'[','{' // replace [ with {
).replace(
']','}' // replace ] with }
).replace(
/\w+(?=[\{\:])/g, // add quotes to object items
function($1) { return '"'+$1+'"'; } // using a lambda function
).replace(
/"\{/g, '": {' // add colon after object items
).replace(
/,(?=\s*\})/g, '' // remove trailing commas
);
// string has been fixed
log(tree);
var obj = JSON.parse(tree);
log('obj.week1 = ' + JSON.stringify(obj.week1));
log('obj.week1.Meth = ' + obj.week1.Meth);
#out {
width: 100%;
height: 170px;
}
<textarea id="out"></textarea>
Related
I am trying to convert a string i receive back from an API into a JSON object in Angular.
The issue is that the string is not normalized to be parsed into JSON easily.
This is the string im working with:
"{rootCause=EJBusinessException: This is a sample exception thrown for testing additional info field, description=This is a more detailed description about the incident., stackTrace=com.springboot.streams.infrastructure.web.heartbeat.HeartbeatService.testServiceNow(HeartbeatService.java:200)}"
When trying to do JSON.parse(myStr) it throws an error due to invalid string format.
Is there an easy way to convert the listed string into a more correct JSON format, getting rid of the '=' and replacing them with ':' instead.
There is more to it than just .replace(/['"]+/g, ''), as even with that the string is not ready to be turned into JSON yet.
Hoping someone more versed in Javascript knows a trick i dont.
You just need to manipulate the string before parsing it remove unecessary string that can cause error to the object like "{" and "}" and split it by "," example is in below.
var obj = {}, str = "{rootCause=EJBusinessException: This is a sample exception thrown for testing additional info field, description=This is a more detailed description about the incident., stackTrace=com.springboot.streams.infrastructure.web.heartbeat.HeartbeatService.testServiceNow(HeartbeatService.java:200)}"
str.split(",").forEach((st, i) => {
pair = st.split("=")
if(pair.length > 1) {
obj[pair[0].replace("{",'').replace("}", '').trim()] = pair[1]
} else {
obj[i] = pair
}
})
console.log(obj)
As commenters have posted, unless you control the API or at least have documentation that output will always follow a specific format, then you are limited in what you can do. With your current example, however you can trim off the extraneous bits to get the actual data... (remove braces, split on comma, split on equals) to get your key:value pairs... then build a javascript object from scratch with the data... if you need json string at that point can just JSON.stringify()
var initialString = "{rootCause=EJBusinessException: This is a sample exception thrown for testing additional info field, description=This is a more detailed description about the incident., stackTrace=com.springboot.streams.infrastructure.web.heartbeat.HeartbeatService.testServiceNow(HeartbeatService.java:200)}"
var trimmedString = initialString.substr(1, initialString.length - 2);
var pairArray = trimmedString.split(',');
var objArray = [];
pairArray.forEach(pair => {
var elementArray = pair.split('=');
var obj = {
key: elementArray[0].trim(),
value: elementArray[1].trim()
};
objArray.push(obj);
});
var returnObj = {};
objArray.forEach(element => {
returnObj[element.key] = element.value;
});
console.log(JSON.stringify(returnObj));
I'm trying to clean up a JSON string (that was converted from a json object) and I found that many people use the .replace() method to do so. However, in doing so my code looked like this:
scrape(url).then(result => {
final = JSON.stringify(result);
final = final.replace(/['"]+/g, "");
final = final.replace(/[{]+/g, "");
final = final.replace(/[}]+/g, "");
final = final.replace(/[:]+/g, ": ");
final = final.replace(/,+/g, ";");
return final;
});
While this method does work returning 'final' in the way i want it, it does not seem very efficient and the code is really clunky. My end goal is to remove quotes, curly brackets, replace ':' with ': ' and change all commas to semi colons. Is there a better/cleaner way to do this?
EDIT:
The input string looks something like this:
{
'$primary': '#ea80fc',
'$p_light': '#ffb2ff',
'$p_dark': '#b64fc8',
'$secondary': '#b64fc8',
'$s_light': '#f9683a',
'$s_dark': '#870000'
}
Given your actual data, where after JSON.parse you have the following structure:
{
'$primary': '#ea80fc',
'$p_light': '#ffb2ff',
'$p_dark': '#b64fc8',
'$secondary': '#b64fc8',
'$s_light': '#f9683a',
'$s_dark': '#870000'
}
turning this into legal SCSS doesn't require a long chain of replaces applied to the JSON string at all. It just requires parsing the JSON to plain JS object, and then iterating over the key/values to form an SCSS string:
function jsonToSCSS(stringdata=``, data={}) {
/* JSON.parse can throw. Always be ready for that. */
try { data = JSON.parse(stringdata); }
catch (e) { console.warn(e); return ``; }
return Object.keys(data)
.map(key => `${key}: ${data[key]};`)
.join('\n');
}
And done. The output of that function is now a normal, formatted string:
$primary: #ea80fc;
$p_light: #ffb2ff;
$p_dark: #b64fc8;
$secondary: #b64fc8;
$s_light: #f9683a;
$s_dark: #870000;
Which you can now write into whatever file you need it written into, either directly, or itself wrapped in formatting:
const SCSS = jsonToSCSS(inputdata);
const qualified = `.someclass { ${SCSS} }`;
More simplified
scrape(url).then(result => {
return JSON.stringify(result.replace(/['"{}]+/g, "").replace(/[:]+/g, ":").replace(/,+/g, ";"));
});
Given the following json data:
[
{
"item":"T1",
"size":10,
"offset":3
},
{
"item":"T2",
"size":20,
"offset":5
}
]
query expr: $.[? ((#size + #offset)<15)].item
the query returns nothing. Anything wrong? it looks like (#size + #offset) is not supported. If so, what is the correct syntax?
I think you might need to try this instead:
$.[? ((#.size + #.offset)<15)].item
Note the dot after each # sign.
With DefiantJS, you can execute XPath on JSON structures.
http://defiantjs.com/
At this site (http://defiantjs.com/#xpath_evaluator), you can paste in your JSON data and try out standard XPath. I have tested your json data and tested this XPath expression, which works as expected:
//*[size + offset > 15]/item
DefiantJS extends the global object JSON with an additional method; "search" and in javascript, it looks like this:
var res = JSON.search(json_data, "//*[size + offset > 15]/item");
console.log(res[0]);
// T2
Hey all im not every good with regexp i was hoping someone could help.
ok so this is the sting "KEY FOUND! [ 57:09:91:40:32:11:00:77:16:80:34:40:91 ]"
And i need to pull "57:09:91:40:32:11:00:77:16:80:34:40:91", now this key can be meany length not just as written here and with or with out the ":"
now the second sting i would like to test and extract is: "[00:00:09] Tested 853 keys (got 179387 IVs)", i would like to pull "00:00:09" and "853" and "179387".
this would be the raw string http://regexr.com?31pcu or http://pastebin.com/eRbnwqn7
this is what im doing now.
var pass = new RegExp('KEY FOUND\!')
var tested = new RegExp('Tested')
var fail = new RegExp('\Failed. Next try with ([0-9]+) IVs')
var data="Look at the link i added"
if (tested.test(data)) {
self.emit('update', mac, {
'keys' : data.split('Tested ')[1].split(' keys ')[0],
'ivs' : data.split('got ')[1].split(' IVs')[0]
});
} else if (pass.test(data)) {
var key = data.split('KEY FOUND! [')[1].split(' ]')[0].split(':').join('');
} else if (fail.test(data)) {
console.log(data);
}
thanks all
Edit:
I have added more the the question to help with the answer
If it is always surrounded by [] then it is simple:
\[([\s\S]*)\]
This will match any characters enclosed by [].
See it in action here.
I'm trying to construct a String in JS that can be passed into JSON as an with a very particular format. Desired result is a string of the following form:
["PNG","350x150","127 KB"]
Where PNG correspond to a particular image's type, where 350x150 is the image's dimensions and where 127 KB is the image's size. Each of these threee values are string variables:
var imgType = getImageType(); // Returns "PNG"
var imgDim = getImageDim(); // Returns "350x150"
var imgSize = getImageSize(); // Returns "127 KB"
var imgDescription = '["' + imgType + '","' + imgDim + '","' + imgSize + '"]';
// Sanity check
alert(imgDescription);
iVO.images[thisImage] = {
"fizz":"buzz",
"imgDesc":imgDescription,
"foo":"bar"
}
alert(JSON.stringify(iVO));
The first alert (on the imgDescription variable) prints:
["PNG","350x150","127 KB"]
So far, so good. However, the minute we pass it to the iVO construct and stringify the resultant JSON, it generates the following output (after I pretty print format it):
{
"images":
{
"4490i45"":
{
"fizz":"buzz",
"imgDesc":"[\"PNG\",\"350x150\",\"127 KB\"]",
"foo":"bar"
}
}
}
All of my double quotes (") have been escaped (\")!!! Also, the value for imgDesc is enclosed in double-quotes, which is not what we want (see desired JSON below):
When I send this JSON back to the server its causing the server to choke.
Not sure what is going on here but I've tried several other suggestions, including replacing my double-quotes with '\x22' instances which didn't help.
Any ideas as to what would fix this to get the desired result from JSON.stringify(iVO)? Ultimately that's the only thing that matters, that the we end up sending the following to the server:
{
"images":
{
"4490i45"":
{
"fizz":"buzz",
"imgDesc":["PNG","350x150","127 KB"],
"foo":"bar"
}
}
}
No escaped double-quotes, and the value for imgDesc is not double-quoted. Thanks in advance!
Why don't you just put imgDescription as regular array
var imgDescription = [imgType , imgDim, imgSize];
Stringify should take care of what you are trying to do, otherwise you are passing imgDescription as a string and stringify would escape the quotes.
e.g.
var imgType = "PNG";
var imgDim = "350x150";
var imgSize = "127 KB";
var d = {
"fizz":"buzz",
"imgDesc":[imgType , imgDim, imgSize],
"foo":"bar"
}
console.log(JSON.stringify(d));
Output:
{"fizz":"buzz","imgDesc":["PNG","350x150","127 KB"],"foo":"bar"}