I Have this kind of JSON Object
"{\"date\": \" 9 Marzo\", \"time\": \" 07:00 - 13:20\", \"descrizione\": \" concerto\", \"alimenti\": [{ \"macchina\":\"si\", \"pollo\":\"no\" }] }";
I want to get exactly the string "macchina" and "pollo", which are the keys text/value (I get the Object from an ajax, so "9 Marzo" would be like response.date), and same for "si" and "no", I cannot arrive to them.
I have tryed console.log(response.alimenti[i][0]); but it's undefined.
i come from the cicle: for (i = 0; i < response.ruoli.length; i++)
This will get you to the strings "macchina" and "pollo":
var json = "{\"date\": \" 9 Marzo\", \"time\": \" 07:00 - 13:20\", \"descrizione\": \" concerto\", \"alimenti\": [{ \"macchina\":\"si\", \"pollo\":\"no\" }] }";
var obj = JSON.parse(json);
for (var k in obj.alimenti[0]) {
console.log(k);
}
or their values:
for (var k in obj.alimenti[0]) {
console.log(obj.alimenti[0][k]);
}
You'd be better off parsing the JSON object and then extracting the string from the javascript object.
i.e var obj = JSON.parse("{\"date\": \" 9 Marzo\", \"time\": \" 07:00 - 13:20\", \"descrizione\": \" concerto\", \"alimenti\": { \"macchina\":\"si\", \"pollo\":\"no\" } }";);
console.log(obj.alimenti[0].macchina);
or pollo
console.log(obj.alimenti[0].pollo);
Also, that object structure is a little weird. You might want to remove the array from within the alimenti to better access the data.
Using response.alimenti[i][0] won't work because alimenti is an array of object(s), not an array of arrays.
This instead:
var alimenti = response.alimenti[0];
console.log(alimenti.maccina);
console.log(alimenti.pollo);
Example: http://jsfiddle.net/zcuwfb9s/
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 have a web page in which contents are loaded dynamically from json. Now i need to find the texts like so2,co2,h2o after the page gets loaded and have to apply subscript for those texts. Is it possible to do this?? If yes please let me know the more efficient way of achieving it.
for example :
var json = { chemA: "value of CO2 is", chemB: "value of H2O is" , chemC: "value in CTUe is"};
in the above json i need to change CO2,H2O and e in CTUe as subscript. how to achieve this??
Take a look at this JSfiddle which shows two approaches:
HTML-based using the <sub> tag
Pure Javascript-based by replacing the matched number with the subscript equivalent in unicode:
http://jsfiddle.net/7gzbjxz3/
var json = { chemA: "CO2", chemB: "H2O" };
var jsonTxt = JSON.stringify(json).replace(/(\d)+/g, function (x){
return String.fromCharCode(8320 + parseInt(x));
});
Option 2 has the advantage of being more portable since you're actually replacing the character. I.e., you can copy and paste the text into say notepad and still see the subscripts there.
The JSFiddle shows both approaches. Not sure why the magic number is 8320 when I was expecting it to be 2080...
So you are generating DOM element as per JSON data you are getting. So before displaying it to DOM you can check if that JSON data contains so2,co2,h2o and if it is then replace that with <sub> tag.
For ex:
var text = 'CO2';
text.replace(/(\d+)/g, "<sub>" + "$1" + "</sub>") ;
And this will returns something like this: "CO2".
As per JSON provided by you:
// Only working for integer right now
var json = { chemA: "value of CO2 is", chemB: "value of H2O is" , chemC: "value in CTUe is"};
$.each(json, function(index, value) {
json[index] = value.replace(/(\d+)/g, "<sub>" + "$1" + "</sub>");
});
console.log(json);
Hope this will helps!
To do this, I would create a prototype function extending String and name it .toSub(). Then, when you create your html from your json, call .toSub() on any value that might contain text that should be in subscript:
// here is the main function
String.prototype.toSub = function() {
var str=this;
var subs = [
['CO2','CO<sub>2</sub>'],
['H2O','H<sub>2O</sub>'],
['CTUe','CO<sub>e</sub>'] // add more here as needed.
];
for(var i=0;i<subs.length;i++){
var chk = subs[i][0];
var rep = subs[i][1];
var pattern = new RegExp('^'+chk+'([ .?!])|( )'+chk+'([ .?!])|( )'+chk+'[ .?!]?$','ig'); // makes a regex like this: /^CO2([ .?!])|( )CO2([ .?!])|( )CO2[ .?!]?$/gi using the surrent sub
// the "empty" capture groups above may seem pointless but they are not
// they allow you to capture the spaces easily so you dont have to deal with them some other way
rep = '$2$4'+rep+'$1$3'; // the $1 etc here are accessing the capture groups from the regex above
str = str.replace(pattern,rep);
}
return str;
};
// below is just for the demo
var json = { chemA: "value of CO2 is", chemB: "value of H2O is" , chemC: "value in CTUe is", chemD: "CO2 is awesome", chemE: "I like H2O!", chemF: "what is H2O?", chemG: "I have H2O. Do you?"};
$.each(json, function(k, v) {
$('#result').append('Key '+k+' = '+v.toSub()+'<br>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
Note:
Anytime you do something like this with regex, you run the chance of unintentionally matching and converting some unwanted bit of text. However, this approach will have far fewer edge cases than searching and replacing text in your whole document as it is much more targeted.
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>
I'm writing a function to replace all occurrences of variables p and q with their respective values without using eval(), however, I'm running into some unexpected behaviors. BTW, I'm using phpjs for the str_replace
Fiddle: http://jsfiddle.net/5Uedt/2/
function table(str){
str=str_replace(["nand","nor","implies","equals","not","xor","and","or","(",")"],[" 3 "," 4 "," 5 "," 6 "," 7 "," 8 ", " 9 ", " 10 ", " ( "," ) "],str).replace(/\s{2,}/g, ' ').trim();
str=str_replace(["3","4","5","6","7","8", "9", "10", "(",")"],["nand","nor","implies","equals","not","xor","and","or","(",")"],str).split(" ");
var vars={p:1,q:1};
for(vars['p']=1;vars['p']>=0;vars['p']--){
for(vars['q']=1;vars['q']>=0;vars['q']--){
alert(str);
newinput=str;
for(var i=0;i<newinput.length;i++){
var token=newinput[i];
if(token.length===1){
console.log(newinput[i]);
newinput[i]=vars[newinput[i]];
}
}
// console.log(n.join(" "));
}
}
}
I have this code for replacing all occurrences, but it's not working. I'm alerting the original string entered in every time, however, the string changes. The expected output of the function is p,and,q repeated 4 times, instead, I have p,and,q, then 1,and,1 repeated 3 times. However, I don't seem to have any assignments to str. Does anyone know why this is happening?
When you set newinput equal to str, you're still referencing that original object. When you change the value later in newinput you affect the str variable.
If you want to clone the object you can iterate over the properties of str like so:
var newinput = {};
for(var key in str) {
newinput[key] = str[key];
}
Thus making a clone of your original object and you won't be affecting it's values. Assuming you don't have objects you want to clone inside your str object. If you do, just run this function recursively.
Updated Fiddle
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"}