Jump to content
Sign in to follow this  
smus

JSON and object

Recommended Posts

If I have a JSON data, can I apply to it as if it is a JS Object, or I should use JSON.parse() first?

Will it skip the property names quotes? ("name":"value" or name:"value")

If there are some associative arrays inside and the structure is complex, is it easier to use array.map() method or it is better to apply to the properties directly?

Share this post


Link to post
Share on other sites

It's correct to wrap property names in quotes in Javascript. JSON stands for "JavaScript Object Notation", after all.

If the JSON is in a string as when returned by AJAX, you need to use JSON.parse() to read it, but if you can just have the JSON right in the code itself, you won't need to parse it.

  • Thanks 1

Share this post


Link to post
Share on other sites

Why is map() method often used for these reasons? Might that be because the structure is complex and I know the name of the property and I am not sure about its hierarchical disposition? For example,

a = { first : ['propertyOne' = 'po', 'propertyTwo' = 'pt'],

     second : [smallObj = {s1:'s1', s2: 's2', s3: 's3'}, smallObj2 = {s1:'s1'}, ['a1', 'a2']],

     third : ['t1', [{'whatIWantToFind':'someInfo'}], t3, 'abcdef']

}

I have to find the 'whatIWantToFind' property inside a object. I know it is inside the object, but I don't know where exactly it is. Do I need to use a map() or any other method for it?

Edited by smus

Share this post


Link to post
Share on other sites

If you're talking about Array.map, that's only available on arrays, not Objects.  Maybe you can convert an Object to an array, but regular Objects don't have a map method.  You can return the keys of an object though and loop through them that way.

It sounds like you need a recursive function that checks if you're dealing with an array or object and searches appropriately.  It would call itself if it found another array or object.

  • Thanks 1

Share this post


Link to post
Share on other sites

Other than what I described?  I'm sure you could come up with something that is more complex, but I don't know why you would.  If you're looking for a built-in recursive object key search, I don't believe there is one.  You would need to roll your own.

  • Thanks 1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...