Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
172
rated 0 times [  177] [ 5]  / answers: 1 / hits: 15632  / 13 Years ago, thu, june 2, 2011, 12:00:00

I'm having some problems with converting some JSON and I'm after some help. This is my problem, I have JSON returned the following:



Example of the JSON recieved (from a CSV file):



[
{
rating: 0,
title: The Killing Kind,
author: John Connolly,
type: Book,
asin: 0340771224,
tags: ,
review: i still haven't had time to read this one...
},
{
rating: 0,
title: The Third Secret,
author: Steve Berry,
type: Book,
asin: 0340899263,
tags: ,
review: need to find time to read this book
},

cut for brevity

]


Now, this is a one dimensional array of objects, but I have a function that I need to pass this to that will ONLY take a multidimensional array. There's nothing I can change on this. I've been looking around the web for conversion and came across this code:



if (! obj.length) { return [];} // length must be set on the object, or it is not iterable  
var a = [];

try {
a = Array.prototype.slice.call(obj, n);
}
// IE 6 and posssibly other browsers will throw an exception, so catch it and use brute force
catch(e) {
Core.batch(obj, function(o, i) {
if (n <= i) {
a[i - n] = o;
}
});
}

return a;


But my code keeps getting stuck on the no object length part. When I iterate through each object, I get character by character. Unfortunately, those field names (rating, title, author), etc are not set in stone and I can't access anything using the obj.Field notation.



I'm stuck on this; is there a way to convert those objects into arrays, or do I have to go back to the beginning and dump JSON?


More From » json

 Answers
19

There is a nice JavaScript library called Undersore.js which does all kind of object/array manipulations.



Using it you could do the conversion as easy as this



_(json).each(function(elem, key){
json[key] = _(elem).values();
});

[#91899] Wednesday, June 1, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
guadalupec

Total Points: 610
Total Questions: 91
Total Answers: 91

Location: Guernsey
Member since Tue, Jul 6, 2021
3 Years ago
;