0

Using this to load the json

var jsonParsed = JSON.parse(localStorage.getItem('test'));

Using this to save

var jsonData = ko.toJSON(viewModel);

Now when readying it in i know i can get my values like sooo...

jsonParsed.AOfficer

(if A officer was a feild with a value) I know that the above code would return the value of the json feild AOfficer but how do i get it to return the name of all the feilds in a json e.g returning that it holds Aofficer rather than its value.

Im wanting to know this because im dynamicly creating forms using the json feild name for the form id and value for form value.

Thanks

2
  • possible duplicate of read name of unknown properties Commented Jun 14, 2012 at 15:09
  • 3
    Note that your problem has nothing to do with JSON. JSON is just a textual representation of data. You seem to be asking for a way to access object properties with unknown names. Reading MDN - Working with Objects might be helpful as well. Commented Jun 14, 2012 at 15:09

2 Answers 2

2

Assuming that jsonParsed is something like:

var field = {
    "field1": "Test data",
    "field2": "Test data"
};

You could do:

for(var field in fields){
    if(fields.hasOwnProperty(field)){
        console.log(field, fields[field]);
    }
 };

That iterates trough all the top-level object props and returns its name, and value.

Sign up to request clarification or add additional context in comments.

1 Comment

+1, but please edit your code to add local assignment to the loop index, as to prevent it from leaking to the global scope (i.e. for(var field in fields)).
1

Use for in loop with optional .hasOwnProperty check to loop over object's properties.

1 Comment

Absolutely correct answer. But just for clarification it's done like this: for(i in jsonParsed) { if(jsonParsed.hasOwnProperty(i) { console.log('Field name: '+i); console.log('Field value: '+jsonParsed[i]); } }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.