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.

5
  • 3
    If you didn't miss the comma after "Science Fiction" by accident, this is not valid JSON. Commented Nov 21, 2011 at 12:31
  • You are missing a comma in your second example. Between "Science Fiction" and "Western". Commented Nov 21, 2011 at 12:33
  • 3
    Your first example is invalid - you have labels inside square brackets. Commented Nov 21, 2011 at 12:34
  • By Mistake, I missed the comma. Kindly ignore that mistake :)..thank you Commented Nov 21, 2011 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 Commented Nov 21, 2011 at 12:49

4 Answers 4

7

Assume

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

then

test.movieCategories[0] // Will be Animation
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks,Gfox. Is it not necessary to have key associated with this? I mean, can I directly access it like test.movieCategories[0] ?
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 ;)
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);

Comments

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?

2 Comments

Hi, By mistake, I missed the comma. It is a valid Json. Thanks for the help.
Ok, then you can follow the link. This question comes up all the time.
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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.