Jump to content

JSON and object


smus

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?

Link to comment
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
Link to comment
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
Link to comment
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
Link to comment
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
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...