How can I make this JSON.stringify work properly - javascript

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.

Related

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));

Accessing a javascript object in D3.js

A javascript data object (JSON notation) has been created with the following content:
"[
{"range":"Shape","values":[{"idx":0,"val":"Random"},{"idx":1,"val":"Line"},{"idx":2,"val":"Square"},{"idx":3,"val":"Circle"},{"idx":4,"val":"Oval"},{"idx":5,"val":"Egg"}]},
{"range":"Color","values":[{"idx":0,"val":"Red"},{"idx":1,"val":"Blue"},{"idx":2,"val":"Yellow"},{"idx":3,"val":"Green"},{"idx":4,"val":"Cyan"}]}
]"
In a next step the index of an ordinal value has to be found in this object. The function should find the index of the value 'Blue' in the range 'Color'.
So the function should have the meta scripting form
f("Color")("Blue")=1
What is the most elegant form to create such a function in the context of D3 and javascript?
Depending on your use case, it might make sense to convert the data structure to a different structure more suitable for direct access. E.g. you could convert your structure to
var data = {
Shape: ['Random', 'Line', ...],
// ...
};
and access it with
data['Shape'].indexOf('Line') // or data.Shape.indexOf('Line')
Or go even one step further and convert to
var data = {
Shape: {
Random: 0,
Line: 1,
// ...
},
// ...
};
and access it with
data['Shape']['Line'] // or data.Shape.Line
What the best solution is depends on the actual use case.
Converting the structure dynamically is pretty straight forward. Here is an example to convert it to the first suggestion:
var newData = {};
data.forEach(function(item) {
newData[item.range] =
item.values.map(function(value) { return value.val; });
});
This would also reduce redundancy (e.g. idx seems to correspond with the element index).
Would this work for you ?
var dataJson = '[ \
{"range":"Shape","values":[{"idx":0,"val":"Random"},{"idx":1,"val":"Line"},{"idx":2,"val":"Square"},{"idx":3,"val":"Circle"},{"idx":4,"val":"Oval"},{"idx":5,"val":"Egg"}]},\
{"range":"Color","values":[{"idx":0,"val":"Red"},{"idx":1,"val":"Blue"},{"idx":2,"val":"Yellow"},{"idx":3,"val":"Green"},{"idx":4,"val":"Cyan"}]}\
]';
var data = JSON.parse(dataJson);
for (each in data){
if ( (data[each].range) === 'Color'){
for (eachVal in data[each].values){
if (data[each].values[eachVal].val === 'Blue'){
alert(data[each].values[eachVal].idx);
}
}
} ;
}
And here is the JSFiddle for you too.

Convert Javascript serialize to Javascript object

I have a textarea with an id of 'dataArrayField' which has code in it, example:
item1: {
type: 'foo',
fieldName: 'bar'}
},
item2: {
type: 'cat',
fieldName: 'dog'
}
I then run var content = $('#dataArrayField').serialize(); on this textarea, which has a nem of codeformat, so the returned data would be something like:
codeFormat=item1%3a+ etc etc
I then use the $.deparam(content) Javascript plugin to turn the serialized string to an
object.
This works, however, the only key that actually is returned, is the codeFormat name, then the value is the text in the field above, so I get something like this:
What can I do so that I can access all the information in the passed object!
If you have a string which represents a javascript object and want to create an actual object from that, one option would be to use eval.
var str = "item1: {type: 'foo',fieldName: 'bar'},item2: {type: 'cat',fieldName: 'dog'}";
var obj = eval('({' + str + '})');
alert(obj.item1.type); // foo!
If a user can enter text that is later displayed to other users, this is probably not a very secure thing to do.
You can either put a valid JSON string in the textarea such as
{"item1":{"type":"foo","fieldName":"bar"},"item2":{"type":"cat","fieldName":"dog"}}
or you can use regular expressions as in THIS WORKING DEMO to clean it up before applying JSON.parse(). As #jibsales has already pointed out, do not use eval():
$(function() {
var val = $('#dataArrayField').val().replace(/[\s']/g,'').replace(/(\w+)/g,'"$1"');
val = '{' + val.replace(/\}\},/g,'},') + '}';
console.log( JSON.parse(val) );
});
Eval is evil. Consider using JSON.serialize() and JSON.parse() instead. The objects entered in the text area will have to be valid JSON but it is much more secure.

d3 - return only data without header

I have a csv data.
DATA :
Time,Count
1377973800,293
1377975600,212
1377977400,129
1377979200,89
1377981000,54
1377982800,21
1377984600,15
I want to return the data in this format.
{
"946705035":4,
"946706692":4,
"946707210":0,
"946709243":2,
"946710714":5,
"946712907":3,
"946713183":4,
"946719001":0
}
I do not want the header Time and Count to be appeared in the json format.
Tried using d3.nest() but the result I got like it starts with key variable which i don't want.
Someone please help me in getting the data in that format.
I believe a code similar to this would do the job:
d3.csv("data.csv", function(error, data) {
var myObject = {};
for (var i=0; i < data.length; i++)
myObject[data[i].Time] = data[i].Count;
};
This gives you data about counts as strings, and if you want numbers, you can just add a "+", which will trigger conversion from string to number:
myObject[data[i].Time] = +data[i].Count;
EDIT: Here is related question on creating object properties dynamically, maybe you can find something useful there too.

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