I want to send json formatted data to jQuery.css() function, and i dont know how to do that.
Later on, i will send more properties, this is just example of my problem.
//Sorry, this var x is actually string that i get when i print my json string
var x = {"transform":"rotate(30deg)","-o-transform":"rotate(30deg)"}
//If i try to do something like this wont work
$("#mainImage").css(x);
//but following works
$("#mainImage").css({"transform":"rotate(30deg)","-o-transform":"rotate(30deg)"})
It probably has to do something that jquery accepts .css( map )
A map of property-value pairs to set.
And i am trying to send single text string, can i somehow convert json to map ?
#Pekka Yes, i am sure that $("#mainImage").css(x); doesnt work.
#Felix That is what i get by calling json = JSON.stringify(data); sorry if it not json data, i am js newbie..
You should parse not stringify JSON before. I tried this one It's works.
var json = '{ "display": "none" }';
var cssObject = JSON.parse(json);
$("#mainImage").css(cssObject);
I've just tried with this code:
$(document).ready(function() {
var x = {"background-color": "yellow"};
$('body').css(x);
});
And basically it works. So the problem can be in sth totally different. Maybe your img element is not there?
http://jsfiddle.net/A4azg/
var cssObj = {
'background-color' : '#ddd',
'font-weight' : '',
'color' : 'red',
"transform":"rotate(30deg)",
"-o-transform":"rotate(30deg)",
"-webkit-transform":"rotate(30deg)"
}
$("#mainImage").css(cssObj);
Related
I have this code:
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
localStorage.setItem('added-items', JSON.stringify(string));
This code will use localStorage.
Here is now the code to get the stored data:
var retrievedObject = localStorage.getItem('added-items');
My problem now is, how can i get the size of the data items? answer must be 2.
How can i get the "Item1" and "Item2"?
I tried retrievedObject[0][0] but it is not working.
And how to add data on it?
so it will be
{"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"Desc":"Item3"}]}
Can I use JSON.stringify?
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
localStorage.setItem('added-items', JSON.stringify(string));
stringify means, take an object and return its presentation as a string.
What you have, is already a string and not a JSON object.
The opposite is JSON.parse which takes a string and turns it into an object.
Neither of them have anything to do with getting the size of an array. When properly coding JavaScript you almost never use JSON.parse or JSON.stringify. Only if serialization is explicitly wanted.
Use length for the size of the array:
var obj = {"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"Desc":"Item3"}]}
console.debug(obj.items.length);
// THIS IS ALREADY STRINGIFIED
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
// DO NOT STRINGIFY AGAIN WHEN WRITING TO LOCAL STORAGE
localStorage.setItem('added-items', string);
// READ STRING FROM LOCAL STORAGE
var retrievedObject = localStorage.getItem('added-items');
// CONVERT STRING TO REGULAR JS OBJECT
var parsedObject = JSON.parse(retrievedObject);
// ACCESS DATA
console.log(parsedObject.items[0].Desc);
To bring clarity to future people that may stumble across this question and found the accepted answer to not be everything you hoped and dreamed for:
I've extended the question so that the user may either want to input a string or JSON into localStorage.
Included are two functions, AddToLocalStorage(data) and GetFromLocalStorage(key).
With AddToLocalStorage(data), if your input is not a string (such as JSON), then it will be converted into one.
GetFromLocalStorage(key) retrieves the data from localStorage of said key
The end of the script shows an example of how to examine and alter the data within JSON. Because it is a combination of objects and array, one must use a combination of . and [] where they are applicable.
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
var json = {"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"firstName":"John"},{"lastName":"Smith"}]};
localStorage.setItem('added-items', AddToLocalStorage(string));
localStorage.setItem('added-items', AddToLocalStorage(json));
// this function converts JSON into string to be entered into localStorage
function AddToLocalStorage(data) {
if (typeof data != "string") {data = JSON.stringify(data);}
return data;
}
// this function gets string from localStorage and converts it into JSON
function GetFromLocalStorage(key) {
return JSON.parse(localStorage.getItem(key));
}
var myData = GetFromLocalStorage("added-items");
console.log(myData.items[2].firstName) // "John"
myData.items[2].firstName = ["John","Elizabeth"];
myData.items[2].lastName = ["Smith","Howard"];
console.log(myData.items[2]) // {"firstName":["John","Elizabeth"],"lastName":["Smith","Howard"]}
console.log(myData.items.length) // 4
JSON.parse is definitely the best way to create an object but I just want to add if that doesn't work (because of lack of support), obj = eval('(' + str + ')'); should work. I've had a problem with a HTML to PDF converter in the past that didn't include JSON.parse and eval did the trick. Try JSON.parse first.
Access your object: obj.items[0].Desc;
var object = Json.parse(retrievedObject);
Now you can access it just like an array
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
If you need more help i have some previous code where i am reading Json from local storage and making a form from that json. This code will help in understanding how to traverse that array
Json stored in localstorage
{"form":[{"element":"input", "type":"text","name":"name","value":"value","min":"2","max":"10"}]}
JavaScript to read that json
function readJson(){
if(!form_created){
add_form();
}
var fetched_json = localStorage.getItem("json");
var obj=JSON.parse(fetched_json);
for(var i=0; i<obj.form.length;i++){
var input = document.createElement(obj.form[i].element);
input.name = obj.form[i].name;
input.value = obj.form[i].value;
input.type = obj.form[i].type;
input.dataset.min = obj.form[i].min;
input.dataset.max = obj.form[i].max;
input.dataset.optional = obj.form[i].optional;
form.insertBefore (input,form.lastChild);
}
alert(obj.form[0].name);
}
I need to push an an object into an array in in a Json file.
To make it simple lets say that my Json looks like this:
var JsonObj = {
"elements" : []
}
I tried Push() method but it didnt work.
tried also to assign to JsonObj.elements[0]= ... it also fails.
How can i make it work?
Try that way, it has to work:
JsonObj.elements.push(1);
FIddle: https://jsfiddle.net/29qa4bfw/1/
This is basic Javascript. nothing to do with Json or jQuery:
var jsonObj = {
"elements" : []
};
jsonObj.elements.push(1);
jsonObj.elements.push(1.5);
jsonObj.elements.push("some text");
jsonObj.elements.push({element: "some element"});
Here's a jsbin to fool around with: http://jsbin.com/hajale/2/edit
im trying to get data out of firebase to be used in a game programmed in JS. The problem is I can never get the data. this is the JSON i'm adding in the editor:
{xcord: 23, ycord: 3543}
This is the JS code im using to try and get the data:
fb.on('child_added', function(snapshot) {
obj = snapshot.val();
alert(obj.xcord);
c1.x = obj.xcord;
c1.y = obj.ycord;
stage.update();
});
When the alert pops up, all i get is 'undefind'. Anyone know whats wrong?
When I console.log your data in the jsbin it shows up as:
{sfws: "{xcord: 23, ycord: 3543}", update: "{xcord:'3435'}", update2: "{xcord: 23, ycord: 3543}"}
Notice those double quotes around the coordinates? Those mean that they're strings, not JSON object.
I guess you store them with something like this:
var coords = document.getElementById('editor').value; // read the text from the input
ref.set(coords);
Any value you read from an input is going to be a string, even if to the human eye it looks remarkably close to a JavaScript object.
You will need to convert the value from a string to a JavaScript object, which you can easily do with JSON.parse. This requires that you enter the object as proper JSON, which means that you'll need to double quote the property names:
'{"xcord": 23, "ycord": 3543}'
You can then parse this JSON back into objects either before you send the value to Firebase:
var text = document.getElementById('editor').value; // read the text from the input
var coords = JSON.parse(text);
ref.set(coords);
Or when you retrieve the string from Firebase:
fb.on('child_added', function(snapshot) {
var text = snapshot.val();
var obj = JSON.parse(text);
alert(obj.xcord);
c1.x = obj.xcord;
c1.y = obj.ycord;
stage.update();
})
Quick fix (not recommended)
If you can't be bothered to convert the data into proper JSON, you can also use eval to get it back into shape. I highly recommend against this, since eval is not just less picky about the quotes; it will also allow code fragments to be injected into your page. But if you feel like ignoring the recommendation, this is the quick fix:
fb.on('child_added', function(snapshot) {
var text = snapshot.val();
eval("obj = "+text);
alert(obj.xcord);
c1.x = obj.xcord;
c1.y = obj.ycord;
stage.update();
})
Your code looks good. Because your alert is coming back 'undefined' leads me to believe something else is wrong. Is the path to your firebase correct?
I have div content and div contains text like javascript Object.
<div class="data-content">{ title: "Yes", value : 4247, color: "#FC4349", total_votes: "10968", percentage: "39%"}, { title: "No", value : 6721, color: "#2980b9", total_votes: "10968", percentage: "61%"}</div>
<script> var data = $('.data-content').text();</script>
currently data value is as a string and I want it as object not string.
Is it possible or any other way to get div content as javascript object?
any help is appreciated.
Just try with:
var data = $('.data-content').text();
var output = JSON.parse('[' + data.replace(/\b([a-z_]+)\b/g, '"$1"') + ']');
What happens here ? Valid JSON format requires keys to be wrapped with apostrophes, so we wrap them with /\b([a-z_]+)\b/g regex.
After that we get only objects separated with comma, so we have to wrap it with [] to make an array. Since now it's valid for JSON parser and we get expected result.
http://jsfiddle.net/8ubFY/
Use JSON.parse() as in:
var transformed = JSON.parse(data);
The linked documentation gives details on how to add error handling if your JSON text is invalid. You can also use jQuery.parseJSON() for better browser support as in:
var transformed = jQuery.parseJSON(data);
Okay, so your JSON was also invalid, see JSON object for documentation of valid JSON objects. I have fixed it up and created a JSFiddle to show the correct code.
I want to put a JSON object into a javascript variable as a sting in order to create a graph.
qm.createGraphData = function() {
$.post("ajax_getGraphDataWebsite ", function(json) {
qm.negativesData = json;
},"json");
qm.data = [{
"xScale":"ordinal",
"comp":[],
"main":[{
"className":".main.l1",
qm.negativesData},{
"className":".main.l2",
qm.negativesData}],
"type":"line-dotted",
"yScale":"linear"}];
}
the string value should be added to the "data" section. Now the object get's added but I need to add the string value to the variable like the sample below:
{"data":[{"x":"3283581","y":"2013-10-16"},{"x":"1512116","y":"2013-10-17"},{"x":"3967","y":"2013-10-18"},{"x":"1094","y":"2013-10-19"},{"x":"853","y":"2013-10-20"},{"x":"1205","y":"2013-10-21"},{"x":"2618700","y":"2013-10-22"},{"x":"3928291","y":"2013-10-23"},{"x":"3670318","y":"2013-10-24"},{"x":"3347369","y":"2013-10-25"},{"x":"2525573","y":"2013-10-26"},{"x":"3224612","y":"2013-10-27"},{"x":"3992964","y":"2013-10-28"},{"x":"3949904","y":"2013-10-29"},{"x":"3568618","y":"2013-10-30"},{"x":"3104696","y":"2013-10-31"},{"x":"3246932","y":"2013-11-01"},{"x":"2817758","y":"2013-11-02"},{"x":"3198856","y":"2013-11-03"},{"x":"3952957","y":"2013-11-04"},{"x":"3934173","y":"2013-11-05"},{"x":"3878718","y":"2013-11-06"},{"x":"3642822","y":"2013-11-07"},{"x":"3186096","y":"2013-11-08"}]}
This would generate the right graph for me. Does anyone know how to convert the json object into a string like above and to send it to the qm.negativesData variable?
// UPDATE
Now I've got the string with the qm.negativesData = JSON.stringify(json); solution
But my qm.negativesdata won't get added to the qm.data variable... i'm getting a console error SyntaxError: invalid property id
I suppose i'm not adding them the right way?
To convert a JSON object into a JSON string, you can try myObject.stringify(), JSON.stringify(myObject), or if you are using a library using the built in function of that library.
So, you could do something like: qm.negativesData = myObject.stringify()
Cheers