How can I add square brackets to my json data source?

779 views
Skip to first unread message

danharr

unread,
Apr 12, 2014, 11:25:48 AM4/12/14
to d3...@googlegroups.com
I am practicing making a real time visual using angular and d3.js.  In the below bl.ock things work as expected when data is obtained using $http.get('data.json'):
The data source looks like so:

[{"name":"alan" , "age":8},
{"name":"alan2" , "age":18}]

But most feeds of JSON that I'm coming across look more like:

{"name":"alan" , "age":8},
{"name":"alan2" , "age":18}

i.e. no opening and closing square bracket.  Is there a way to have http.get read the data despite the lack of square brackets?
Thanks!

Nick Guenther

unread,
Apr 12, 2014, 3:53:46 PM4/12/14
to d3...@googlegroups.com, danharr


danharr <danjpha...@gmail.com> wrote:
>I am practicing making a real time visual using angular and d3.js. In
>the
>below bl.ock things work as expected when data is obtained using
>$http.get('data.json'):
>http://bl.ocks.org/danharr/10540505
>
>The data source looks like so:
>
>*[*{"name":"alan" , "age":8},
>{"name":"alan2" , "age":18}*]*
>
>But most feeds of JSON that I'm coming across look more like:
>
>{"name":"alan" , "age":8},
>{"name":"alan2" , "age":18}
>
>i.e. no opening and closing square bracket. Is there a way to have
>http.get read the data despite the lack of square brackets?
>Thanks!

Is your data source not giving you valid json? If not, can you fix that
instead? There's probably bigger bugs lurking if its not passing a
standard format. If you give us a link to one of these strange feeds
(and I do think they're strange; proper json will not be like you show)
we can maybe tell if there is something misspecified about your calls.

If the only bug is literally just the lack of [ ] (if!), in the worst
case, you can set data="[" + data + "]" and parse it with JSON.parse. I
see where you are confused a bit though; $http.get is not a d3 call; it
is an AngularJS call. The docs for it say
> If JSON response is detected, deserialize it using a JSON parser.

To go this route you need to disable that deserialization. The docs say
you can tell Angular to turn off the deserialization with
$http.get('data.json', {transformResponse: []})

Best of luck to your learning,
-Nick Guenther
4A Stats/CS
University of Waterloo

danharr

unread,
Apr 13, 2014, 7:59:02 AM4/13/14
to d3...@googlegroups.com, danharr, ngue...@uwaterloo.ca
thanks for the guidance

An example of data I'm trying to use which I feel is missing square brackets (though maybe not) is:
Unless I save this data manually,say into mydata.json, and add square brackets I can't read in the data.

I'll read up on transformResponse and reply if I get any success

Thanks!
Reply all
Reply to author
Forward
0 new messages