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
Related
I want to ask because I doubt it. Can I put a JSON inside JSON? Like this.
var json = {
test = { "name":"test", "age":"99" };
};
So I can use it like this :
console.log(json.test.name);
Thank you for your answer.
Yes, your syntax is just wrong:
var json = {
test: { "name":"test", "age":"99" }
^^ ^^ no semi-colon
};
And for clarification, what you have is a Javascript Object Literal, not JSON. JSON is a string representation of a Javascript Object**
** Simplified explanation. Full details http://json.org/
Please correct your json :
var jsonVar = {test :{ "name":"test", "age":"99" }};
Also avoid creating a variable using reserved words like json. use jsonVar, jsonVal etc.
console.log(jsonVar);
console.log(jsonVar.test);
console.log(jsonVar.test.name);
console.log(jsonVar.test.age);
and their respective ans in firebug console.
Object { test={...}}
Object { name="test", age="99"}
test
99
For some reason I just can't seem to be able to display properties from this JSON string:
http://www.easports.com/iframe/fifa14proclubs/api/platforms/PS4/clubs/51694/members
I've sat here for the last 2-3 hours trying out different ways to select single properties such as the name of the first person in the array. A couple selectors I've tried:
$("#output").append(data.raw[0].176932931.name);
$("#output").append(data.raw[0][0].name);
I always get the same error. "data.raw[0] is undefined". The JSON string is valid, I'm able to output the whole string to my page using:
document.getElementById('output').innerHTML=data.toSource();
Parsing it into a JSON object gives me another error because it already is a JSON object. By using console.log(data) I'm able to view the JSON object properly in Firebug.
data is the name of the Javascript JSON object variable that is being returned from my YQL statement.
Please, if anyone could provide some examples as to how I should go about accessing the properties of the above JSON string, that would be great.
UPDATE:
Here's the callback function from my YQL statement:
function cbfunc(json)
{
if (json.query.count)
{
var data = json.query.results.json;
$("#output").append(data.raw[0]["176932931"].name);
}
You need to use bracket notation, as identifiers starting with digits are invalid
$("#output").append(data.raw[0]["176932931"].name);
as "176932931" is an integer key so you have to access like json["176932931"].
For example
data.raw[0]["176932931"].name
see fiddle here
.count isn't a property of a json object. Try this:
var something = {"raw":[{"176932931":{"name":"Shipdawg","blazeId":176932931,"clubStatus":0,"onlineStatus":0,"nucleusId":2266699357,"personaName":"Shipdawg"},"182141183":{"name":"Beks8","blazeId":182141183,"clubStatus":0,"onlineStatus":0,"nucleusId":2272736228,"personaName":"Beks8"},"219929617":{"name":"ChelseaFC_26","blazeId":219929617,"clubStatus":0,"onlineStatus":0,"nucleusId":2304510098,"personaName":"ChelseaFC_26"},"457588267":{"name":"Lazy__Rich","blazeId":457588267,"clubStatus":0,"onlineStatus":0,"nucleusId":2495578386,"personaName":"Lazy__Rich"},"517570695":{"name":"x0__andrew__0x","blazeId":517570695,"clubStatus":0,"onlineStatus":1,"nucleusId":2549150176,"personaName":"x0__andrew__0x"},"912396727":{"name":"mizz00-","blazeId":912396727,"clubStatus":0,"onlineStatus":1,"nucleusId":1000118566560,"personaName":"mizz00-"},"915144354":{"name":"MisterKanii","blazeId":915144354,"clubStatus":2,"onlineStatus":0,"nucleusId":2281969661,"personaName":"MisterKanii"}}]}
function cbfunc(json)
{
if (json.raw.length)
{
$("#output").append(json.raw["0"]["176932931"].name);
}
}
cbfunc(something);
Tell me if this works for you:
function cbfunc(json)
{
$each(json, function(key, object){
console.log(key, object);
});
var raw = query.results.json.raw;
console.log(raw );
// uncomment it if you want some extra check.
if (/*typeof data.raw !=='undefined' && */data.raw.length > 0)
{
//console.log(data.raw[0]["176932931"].name);
//$("#output").append(data.raw[0]["176932931"].name);
}
}
If this works for you there's no need to reference the object to data, simply use the object its self.
JS fiddle: http://jsfiddle.net/q8xL3/2/
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
I'm trying to get the attributes of a div and trying to put it in a json format.
For example if I have a div and its attributes are:
api="something" data-page="5" data-tag="blah"
So I'm trying to put it in this format in json:
{"api":"getArticles","parameters":{"param1":"value 1","param2":value2... }}
Here's the code I've written so far, but I'm not sure if I'm doing it right because its return [object Object]. How do I check if what I'm doing is correct and see the json array in the above mentioned form?
JSfiddle link: http://jsfiddle.net/ithril/mCNbW/4/
var arr = $("div").get(0).attributes, attributes = [];
var l;
var attrinames;
var attrivalues;
var api;
for(var i = 0; i < arr.length; i++) {
if(arr[i].name.indexOf("data-")==0){
l=arr[i].name.lastIndexOf("data-",0)+"data-".length;
attrinames=arr[i].name.substr(l);
if(attrinames!="apicall"){
attrivalues=arr[i].value;
attributes.push({attrinames:attrivalues});
}
else
api=attrivalues;
}
}
var json=[]
json.push({"api":api,"parameters":attributes});
alert(json);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class="divload" data-apicall="anything.php" link="" data-page="5" data-tag="stuff">
JSON.stringify(data) will serialize the data contained within the Object.
See updated jsFiddle.
Don't use alert(variable). Use console.log(variable) and use a debugger instead. Hit F12 and view the console tab to see the results of console.log(). Also, I'd avoid naming a variable json because there is a global object named JSON.
Build the JS object whatever you want, then pass it to a JSON stringtifier, like this one:
https://github.com/douglascrockford/JSON-js
Don't try to build yourself a stringfier, because you will make mistakes, is best to use libraries or something builting.
JSON format is text, and you are building a object, you need to serialize that object to text using the json format.
Normally it will look like that:
JSON.stringify(data)
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);