String with variables and values to Objects/Array - javascript

White iterating through JSON data, I've some variables as flat strings with property name and values
row 1
"propertyurl: http://link1, imageurl: http://image1.jpg"
row 2
"propertyurl: http://link2, imageurl: http://image2.jpg"
row 3
"propertyurl: http://link3, imageurl: http://image3.jpg"
I'd like split and return an object as follows (basically JSON format)
{ propertyurl: "link1", imageurl: "image2.jpg" }
I've tried
for(var i=0; i<entries.length; i++) {
console.log(JSON.parse(entries[i].content.$t));
}
Edit:
added http:// to the links

If the string format is that predictable, you split the line on the commas and the on the colons:
var s = "propertyurl: link3, imageurl: image2.jpg"; // One of the rows you've shown in the OP
var obj = {};
s.split(",").forEach(function (property) {
var kv = property.split(": ");
obj[kv[0].trim()] = kv[1].trim();
});
Essentially what you are doing is looping over the string and assigning the values as they appear to obj, which you can then use.
Edit:
Added space after the colon

Your json string is missing quotes and is not valid json. image2.jpg is not "image2.jpg".
You need JSON.parse('{"propertyurl": "link3", "imageurl": "image2.jpg"}');

Related

Javascript dynamic string template to title

I have a string template that backend sends dynamically. Each table tab has a different label_pattern when user want to edit or delete a row we should build the title based on this pattern..
At the moment we use the hash id in the title (pop-up, when want to edit or delete a table row) but it is not descriptive..
The string template look like this:
label_pattern: "{{code}}, {{description}}, {{category}}"
We can also have access through props to the row we want to delete or edit and the object looks like this:
{
category: "Fruit"
code: "AP"
description: "Green Apple"
hash: "b45516ddda8566ee"
}
I used the split function to create an array from the label pattern:
 ['{{code}},', '{{description}},', '{{category}},']
The reason why it is important because the label_pattern on a different table tab maybe looks differently. So we always have to compare the active table pattern because they adjusted to the current tab's row object.
I can access the active tab pattern and the row's data too. I just don't know how to iterate, map and replace through the pattern array in order to build the title text based on this..
You can simply achieve it by using RegEx with the help of String.replaceAll() method.
Live Demo :
const label_pattern = "{{code}}, {{description}}, {{category}}";
const obj = {
category: "Fruit",
code: "AP",
description: "Green Apple",
hash: "b45516ddda8566ee"
};
const reg = /{{|}}/g
const splittedStr = label_pattern.replaceAll(reg, '').split(',');
function buildLabel(splittedStr, obj) {
const label = splittedStr.map(item => obj[item.trim()]);
return label.join(' ')
}
console.log(buildLabel(splittedStr, obj));
I think this should do the trick:
let label_pattern = "{{code}}, {{description}}, {{category}}".split(",");
let label_array = label_pattern.map((value) => { return value.trim().substring(2, value.trim().length-2) });
This considers your input string will always be in this format:
"{{label1}}, {{label2}}, {{label3}} ..."
Explanation:
I split the string with commas as you mentioned, then map each label we have and remove any trailing spaces. Then we find the substring in each string removing two characters from front and back.
Edit: Sorry for the bad indentation and formatting, I solved it in the console.
Edit 2: In order to extract the values from an object whose keys are as a string in the array (label_array in our case) the following code will work:
let obj = {
"category": "Fruit",
"code": "AP",
"description": "Green Apple",
"hash": "b45516ddda8566ee"
}
let values = label_array.map((key) => { return obj[key]});
In my execution the values was: ['AP', 'Green Apple', 'Fruit']
You can use a regex and a replacer function to replace the text with the objects properies:
const obj =
{
category: "Fruit",
code: "AP",
description: "Green Apple",
hash: "b45516ddda8566ee",
};
const label_pattern = "{{code}}, {{description}}, {{category}}";
let label = label_pattern.replace(/{{(?<prop>\w+)}}/g, function(match, p, offset, string, groups)
{
return obj[groups.prop];
});
console.log(label);

How can I make this JSON.stringify work properly

I have a small issue to make my arrays into the json I want to. I have made this code:
var arrData = [{label:Test,value:199.12}, {label:Test2,value:1024}]
var data = [];
for (var i = 0; i < arrData.length; i++) {
data.push(JSON.stringify({
label: arrData[i][2],
value: arrData[i][3]
}).replace(/\"/g, "").replace("\\r", ""))
}
It also does the job properly. But I do want it to be in this format:
{ label: 'Food', value: 90 },
I want to have the ' ' on the label data and I want to remove the double "" punctuation mark outside the json. Since my current json looks like this:
"{label:Test,value:199.12}", "{label:Test2,value:1024}",
{ label: 'Food', value: 90 } isn't valid JSON so you cannot create it using JSON.stringify.
It isn't any standard serialisation format (although it is a valid JavaScript literal) so if you want to serialise data to it, you'll need to write a custom serialiser.
You could loop over the properties of the object and append them, the associated values, and whatever quotes and commas your format demands, to a string.

Json key has '#' Special character

Currently I need the URL for an image and I am getting it through the JSON file. I am not sure to acquire the key that has the URL due to the key having a # at the start. Here is the JSON:
{
"#text":"https://lastfm-img2.akamaized.net/i/u/34s/3ed37777196a6f2c29c02a1a58a93e4d.png",
"size":"small"
},
{
"#text":"https://lastfm-img2.akamaized.net/i/u/64s/3ed37777196a6f2c29c02a1a58a93e4d.png",
"size":"medium"
}
Same as with every other time you encounter some JSON string!
The # is an invalid character in a property name, work around is the bracket notation: «object»[property] --> «array»[index]['#text'].
We can use forEach to extract the results.
var string = '[{"#text":"https://lastfm-img2.akamaized.net/i/u/34s/3ed37777196a6f2c29c02a1a58a93e4d.png","size":"small"},{"#text":"https://lastfm-img2.akamaized.net/i/u/64s/3ed37777196a6f2c29c02a1a58a93e4d.png","size":"medium"}]';
var parsed = JSON.parse(string);
//parsed is an array, we can loop over it
parsed.forEach(function(obj) {
console.log(obj['#text']);
});
Even prettier would be if you can select from the array based on size:
var string = '[{"#text":"https://lastfm-img2.akamaized.net/i/u/34s/3ed37777196a6f2c29c02a1a58a93e4d.png","size":"small"},{"#text":"https://lastfm-img2.akamaized.net/i/u/64s/3ed37777196a6f2c29c02a1a58a93e4d.png","size":"medium"}]';
function getImageUrlBySize(size, json) {
var parsed = JSON.parse(json);
return parsed.find(function(element) { //modern browsers only (no IE)
return element['size'] == size;
})['#text']; //add text here since find returns the full item
}
console.log(getImageUrlBySize('small', string));

Get comma separated string from array

I have the following JSON in JS.
{
"url":"http://example.com/main.aspx",
"report_template_id":"1",
"interval_secs":"86400",
"analysis_type":"lite",
"email":"rokumar#example.com",
"alerts":["num_domains", "med_load_time", "avg_load_time", "tot_req"]
}
I want the list of alerts to be removed and replaced with comma separated values as follows.
{
"url":"http://example.com/main.aspx",
"report_template_id":"1",
"interval_secs":"86400",
"analysis_type":"lite",
"email":"rokumar#example.com",
"alerts":"num_domains,med_load_time,avg_load_time,tot_req"
}
Just adding all the steps:-
1). Taking your JSON in a variable.
data = {"url":"http://example.com/main.aspx","report_template_id":"1","interval_secs":"86400","analysis_type":"lite","email":"rokumar#example.com","alerts":["num_domains","med_load_time","avg_load_time","tot_req"]};
2). Parse JSON data to object. Assuming the JSON is a string initially do a typeof(data) to be clear.
data = JSON.parse(data);
3) Change list of alerts to comma separated values
data.alerts = data.alerts.join(',');
4) Convert back to string
data = JSON.stringify(data)
So data will look like
{
"url": "http://example.com/main.aspx",
"report_template_id": "1",
"interval_secs": "86400",
"analysis_type": "lite",
"email": "rokumar#example.com",
"alerts": "num_domains,med_load_time,avg_load_time,tot_req"
}
Note:- If you will just say join() then also it will work, because default delimiter is , only, just to clarify I have given that.

How to calculate length of nested JSON?

Here I load a JSON into a variable. But I am unable to find the length of the nested JSON.
var JVarible = [{"key":{"kind":"Comment","id":5992578889547776},"categoryId":0,"userName":"Shana Deepak","userId":"cpshana","comment":"hi.fghfghfgh ","createDate":"Sep 16, 2013 7:07:36 AM","url":"https://graph.facebook.com/100000840303512/picture?type\u003dsmall","networkType":"facebook","status":1,"nestmsgs":{"value":"[{\"key\":{\"kind\":\"Nestmsg\",\"id\":5914238686068736},\"commentId\":5992578889547776,\"userName\":\"Shana Deepak\",\"userId\":\"cpshana\",\"message\":\"dfgdfgfdg\",\"createDate\":\"Sep 16, 2013 7:22:01 AM\",\"url\":\"https://graph.facebook.com/100000840303512/picture?type\\u003dsmall\",\"networkType\":\"facebook\",\"status\":0},{\"key\":{\"kind\":\"Nestmsg\",\"id\":5281469744283648},\"commentId\":5992578889547776,\"userName\":\"Shana Deepak\",\"userId\":\"cpshana\",\"message\":\"gfdgdfgfd\",\"createDate\":\"Sep 16, 2013 7:12:25 AM\",\"url\":\"https://graph.facebook.com/100000840303512/picture?type\\u003dsmall\",\"networkType\":\"facebook\",\"status\":0}]"}}];
var i=0;
for (i=0; i<JVarible.length;i++)
{
alert(JVarible[i].['nestmsgs'].length)
}
First of all, JVarible does not contain JSON. It contains a JavaScript array. But one of the values inside that array is indeed JSON (contained in a string).
Your question is not very clear, but it seems you want to get the number of messages within each object. nestmsgs is actually an object with one property, value. value has a string containing JSON as value.
You first have to parse the JSON, which results in an array, and then you can determine its length:
for (var i = 0; i < JVarible.length; i++) {
var msgobj = JVarible[i].nestmsgs;
msgobj.value = JSON.parse(msgobj.value);
alert(msgobj.value.length)
}
Something like this?
Object.keys(JVarible[0]) //returns ["key", "categoryId", "userName", "userId", "comment", "createDate", "url", "networkType", "status", "nestmsgs"]
Object.keys(JVarible[0]).length //returns 10

Categories

Resources