0

eg if variable jsonstring contains

{"prod_name":"GM","quantity":100,"price":54.5,"type":"Limit"} 

for a code like

 var obj= JSON.parse(jsonstring); 

Without knowing the string content is there a way to extract the property/ value names?

1
  • 1
    for ... in, Object.keys() ... Commented May 6, 2014 at 14:19

2 Answers 2

2

You can loop through the object properties.

for ( var prop in obj ) { if ( obj.hasOwnProperty(prop) ) { console.log( prop + ': ' + obj[prop] ); } } 
Sign up to request clarification or add additional context in comments.

4 Comments

hasOwnProperty isn't really necessary.
This way prevents 'walking' up the prototype chain, only checking the properties directly on the object itself.
@Andy, if they (or any third-party scripts) have extended the Object prototype it is necessary.
It's JSON, so I disagree.
1

In JavaScript 1.8.5, Object.getOwnPropertyNames returns an array of all properties found directly upon a given object.

Object.getOwnPropertyNames ( obj ) 

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.