I have below jsoncode
{"0":{"category":"screensets","position":"top","rotate":"180","3d_file":"3d_deg_180.obj","height":"10","width":"10","x":"299","y":"166","current_roate":"0","comp_color":""},"width":"640","height":"640","name":"Test Drawing","size":"40","screen":"Conference set"}
How to decode in array format using jquery?
Small Example May be you help full
var j ='[{"id":"1","name":"test1"},{"id":"2","name":"test2"},{"id":"3","name":"test3"},{"id":"4","name":"test4"},{"id":"5","name":"test5"}]';
var json = $.parseJSON(j);
$(json).each(function(i,val){
$.each(val,function(k,v){
console.log(k+" : "+ v);
$('.Record').append(k+" : "+ v+'<br>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="Record"></div>
Seems like you are trying to turn all the contents of an object into an array, if I'm understanding correctly. This could be problematic.
Arrays in Javascript can't have named indices, so you can't have something like ['width'=>640] as you could in PHP. If that is what your looking for then you need another object to follow the following format {width:640}, much like you have right now. In other words, you need an object. Look at this for more details.
My recommendation is to figure out, or at least tell us, the purpose this JSON will accomplish as it is not a simple data structure.
Related
I have an array of JSON plots which I store in MySQL. When I retrieve this information from MySQL it is given as one long string. How can I restore this back into an array of JSON objects using Javascript? I'm running this using NodeJS and MySQL package.
My data is returned like the following:
'[{"x":0,"y":0},{"x":1,y:1},{"x":2,"y":2}]'
What I would like to be able to do is use the data like:
var data = [{"x":0,"y":0},{"x":1,"y":1},{"x":2,"y":2}];
console.log(data[0].x);
I've had a try using JSON.parse and originally stored the data using JSON.stringify on the array, but it is not behaving as I would expect.
Are there any methods or packages available to handle this?
Edit: I realize now that this is not JSON but rather objects. Apologies for the wrong terminology here, but my problem still remains.
var data = new Function ('return ' + dataString)();
I'm newbie at JavaScript, and i'm having some issues using parse Json.
I have one array in PHP, and i'm passing the values from the PHP to JavaScript.
The problem is that i inserted the values inside a While loop, and When i get multiple values:
Value 1
Value 2
I receive this:
[{"id":"1","value":"1","month":"2"}, {"id":"1","value":"2","month":"2"}]
And to print the values i have to do that:
alert(obj[0].name);
alert(obj[1].name);
And i want to print the values together
How can i use a for loop in this situation? I just need a simple example to implement on my code, thanks.
I think you can get the length of the array using obj.length and then iterate over them and put all the values in a single variable. and then print/alert.
var len= obj.length;
var str="";
for(i=0;i<=len;i++)
{
str+=obj[i].name+' ';
}
something in the line, tied to your requirements.
Hope it helps.
Well, sorry for my bad grammar, but any help will be much appreciated..
Ok, here I'm trying to encode string by using json inside PHP then using JavaScript to read the json string. It will have 2 cases here.
The first one is, the application will running normally, so does the encode. The json string will be like this :
{"employee":
[{"id":"1","firstName":"aaa","lastName":"abc","timeIn":"08:00:00","timeOut":"17:00:00"},
{"id":"2","firstName":"bbb","lastName":"def","timeIn":"08:00:00","timeOut":"16:45:00"}]}
and the second one is, the PHP can't read the MySQL database, so in PHP the json encode will be like this :
{"errorProcess":{"text":SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it. }}
The question is, in JavaScript how can I make an IF statement in JavaScript based on the result string in json?
Maybe it will be like this, but I don't know how to write it in JavaScript.
IF (in json string has employee){then result}
else if(in json string has errorProcess){then result}
Thanks for your help
You can check for errorProcess key using
if(json.hasOwnProperty('errorProcess')){
//do struff
}
JSON keys and values are accessed using dot (.) notation in Javascript. Assuming you already have the JSON as an object (not a string), you can simply write
if (json.employee) {
// do something
}
else if (json.error) {
// do something else
}
where json is a variable referencing your returned JSON from the php.
If your JSON is still in string format, you need to parse it into an object. This can be done with the built in JSON object.
var json = JSON.parse(jsonAsString);
First you need to parese JSON like this
var jsonObject= jQuery.parseJSON(yourJsonObj);
if(jsonObject.hasOwnProperty('employee')){
// Add your code
}else if(jsonObject.hasOwnProperty('errorProcess')){
// Add your code
}
I don't have much experience with JSON, I want to know if something like this is possible.
{
"variable": "A really long value that will take up a lot of space if repeated",
"array": [variable, variable, variable]
}
Obviously that isn't valid, but I want to know if there is a way to do this. I tried using "variable" but of course that just sets the array item to the string "variable". The reason I want to do this is I need to repeat long values in a multidimensional array, which takes up a lot of space.
Thanks.
If you are willing to do some post-processing on the JSON after parsing it, then you can use a token value in your array, and replace the token after parsing with the variable. Example:
{
"variable": "A really long value",
"array": ["variable", "variable", "variable"]
}
Then, in your code that parses:
var obj = JSON.parse(str);
for (var i=0; i<obj.array.length; i++)
{
obj.array[i] = obj[obj.array[i]];
}
Are you worried about space in the output, or in the object created from the JSON? In the latter case, it's likely that the string values will be coalesced when the parsing happens.
If you're concerned about the size of the JSON, then you'll probably either want to change to another format, or de-duplicate the strings in the JSON.
You could add an object to your JSON data that maps ID numbers to strings, then use the IDs to represent te strings.
There is no way to do this in pure JSON (full spec here).
If you wanted to do something like that you might want to look into templating tools such as Handlebars
you will get your answer here jason tutorial for beginners
example:
var data={
"firstName":"Ray",
"lastName":"Villalobos",
"joined":2012
};
I'm in the following situation. The current url looks like the following:
/categories/Art
And I'm using name = location.pathname.split('/')[2] in order to grab the Art portion of the URL. Then, I send an AJAX the following path back to the controller: http://localhost:3000/sort?sortMethod=name&category=name or date, whichever link is clicked on.
Now in my controller I can use sort = params[:category] to get the string name, yet what I'd like to do with this string is sort an array by it. #categories is an array of objects and I'd like to call .sort_by(&:sort) yet it doesn't recognize the string value of sort = name. So now I'd like to convert this string into a proc in order to sort the array. Anyone know how I accomplish this?
Any help is greatly appreciated!
Convert it to a symbol first and then use Symbol#to_proc:
#categories.sort_by(&sort.to_sym)
However be sure that the users can't call anything malicious on your objects like:
http://localhost:3000/sort?sortMethod=destroy
One way of protecting yourself is to use attribute_accessible definitions in your model and then do
#categories.sort_by(&sort.to_sym) if Category.accessible_attributes.include? sort.to_sym
The problem is not entirely clear, so you may need to adjust the following solution. However, the basic idea is taht it's possible to do something like:
Category.all.sort_by {|category| category.method(params[:category]).call }
Also, the "Art" portion of your url is available in Rails' params hash as params[:action], so you don't have to do location.pathname.split('/')[2].