0

I have an object which has strings as values, but I want to convert them to objects.

Here is a working example of the object in question.

var test = {
    val1: "[{"test":"testval","test2": "testval2"}]",
    val2: "[{"test":"testval","test2": "testval2"}]",
    val3: "[{"test":"testval","test2": "testval2"}]"
}

I have tried JSON.parse(test) and...

var output;
for(var key in test){
    output += JSON.parse(test[key]);
}

TLDR: Want to "unstring" the object values to make them an (sub)object.

3
  • 1
    what do you want to achieve with output += ? Commented Jan 3, 2017 at 13:57
  • All and everything is an object in JavaScript. Commented Jan 3, 2017 at 13:57
  • This is not valid JS: val1: "[{"test":"testval","test2": "testval2"}]", - perhaps you meant val1: '[{"test":"testval","test2": "testval2"}]', Commented Jan 3, 2017 at 14:04

4 Answers 4

2

How about:

for(var key in test){
    test[key] = JSON.parse(test[key]);
}
Sign up to request clarification or add additional context in comments.

Comments

2

Operator =+ do not work with objects as you expect. Check {a:1} + {b:2} in console.

You should create empty object. Then set parsed JSON strings as properties.

This will work.

var output = {};
for(var key in test){
    output[ key ] = JSON.parse(test[key]);
}

Comments

1

It doesn't work because you are trying to parse an object and not a string. JSON.parse doesn't work on object but a JSON string.

Also, there is a syntax error that you are using " instead of ' to specify the JSON strings. Change your code as below:

var test = {
    val1: '[{"test":"testval","test2": "testval2"}]',
    val2: '[{"test":"testval","test2": "testval2"}]',
    val3: '[{"test":"testval","test2": "testval2"}]'
}

var output = {};
for(var key in test){
  output[key]= JSON.parse(test[key]);
}

console.log(output);

Comments

1

This can be done with a for-loop.

Your "String" values do not seem to be valid JavaScript. Please make sure you start with a single quote or escape the double-quotes.

var test = {
    val1: '[{"test":"testval","test2":"testval2"}]',
    val2: '[{"test":"testval","test2":"testval2"}]',
    val3: '[{"test":"testval","test2":"testval2"}]'
};

// Convert all values to objects.
Object.keys(test).forEach(key => test[key] = JSON.parse(test[key]));

// Print modified object.
console.log(JSON.stringify(test, null, 4));
.as-console-wrapper { top:0; max-height:100% !important; }

Comments

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.