2

Json Array as following is easy to parse,

{
    "movieCategories": [
       "a" : "Animation",
         "b" :"Romance",
        "c" :"Science Fiction"
       "d" : "Western"
    ]
}

Now,I have a Json response as following which is stored in movies.json file.

{
    "movieCategories": [
        "Animation",
         "Romance",
        "Science Fiction",
        "Western"
    ]
}

I am not sure how to parse the above json array. Kindly help.

Thank you.

hugomg
  • 68,213
  • 24
  • 160
  • 246
Gendaful
  • 5,522
  • 11
  • 57
  • 76
  • 3
    If you didn't miss the comma after `"Science Fiction"` by accident, this is not valid JSON. – nfechner Nov 21 '11 at 12:31
  • You are missing a comma in your second example. Between "Science Fiction" and "Western". – Stefan Nov 21 '11 at 12:33
  • 3
    Your first example is invalid - you have labels inside square brackets. – N3dst4 Nov 21 '11 at 12:34
  • By Mistake, I missed the comma. Kindly ignore that mistake :)..thank you – Gendaful Nov 21 '11 at 12:43
  • @user515990: You should tell us how you are running things (we can't read your mind). You should also be sure you don't have tons of spelling and syntax errors on critical parts of your question – hugomg Nov 21 '11 at 12:49

4 Answers4

7

Assume

    var test = {
    "movieCategories": [
        "Animation",
         "Romance",
        "Science Fiction"
        "Western"
    ]
}

then

test.movieCategories[0] // Will be Animation
Gfox
  • 307
  • 1
  • 6
  • Thanks,Gfox. Is it not necessary to have key associated with this? I mean, can I directly access it like test.movieCategories[0] ? – Gendaful Nov 21 '11 at 12:41
  • You're welcome.Yup if keys are not specified then it is considered as usual javascript Array and you can iterate through it as you do usually ;) – Gfox Nov 21 '11 at 12:46
3

Download json2.js from here https://github.com/douglascrockford/JSON-js Include it on your page. Use like this

jsonobj = JSON.parse(jsonstring);
jsonstring = JSON.stringify(jsonobj);
Moe Sweet
  • 3,683
  • 2
  • 34
  • 46
1

According to JSLint this is invalid JSON. There is a "," missing:

{ "movieCategories": [ "Animation", "Romance", "Science Fiction", "Western" ] }

For the rest see: Is it possible to parse JSON with javascript?

Community
  • 1
  • 1
PiTheNumber
  • 22,828
  • 17
  • 107
  • 180
1

you can only use the eval like

<html>
<div>
<script language="javascript">
  var arr = '[{ "movieCategories": [ "Animation", "Romance", "Science Fiction" ,"Western" ] }]';
  var b = eval(arr)[0];
  alert(b.movieCategories);
</script>
</div>
</html>
shenhengbin
  • 4,236
  • 1
  • 24
  • 33