0

I want to create a JSON object words which further contains a list of objects s and e with different values as follows:

words = {
    "a1": { s: 1.5, e: 2 },
    "a2": { s: 2.1, e: 2.4 },
    "a3": { s: 2.5, e: 3 },
    "a4": { s: 3.5, e: 3.8 },
    "a5": { s: 3.9, e: 4.5 },
    "a6": { s: 4.8, e: 5.2 },
    "a7": { s: 5.3, e: 5.3 },
    "a8": { s: 6.5, e: 7 },
    "a9": { s: 7.2, e: 8 },
    "a10": { s: 8.1, e: 8.4 }
};

I need to add these values using a for loop. I have applied the following solution for this:

var words = {};
var xyz = [1.5,2,2.1,2.4,2.5,3,3.5,3.8,3.9,4.5,4.8,5.2,5.3,5.3,6.5,7,7.2,8];
words = '{';
for (var i = 0; i <= 10; i++) {
    if (i == 10)
        var obj = '\"a' + i + '\"'+': { s:' + xyz[i] + ', e:' + xyz[i + 1] + '}';
    else
        var obj = '\"a' + i + '\": { s:' + xyz[i] + ', e:' + xyz[i + 1] + '},';

    words = words + obj;
}
words = words + '}';

$.parseJSON(words);

But this generates an error of:

Uncaught SyntaxError: Unexpected token s**

I am not able to create the object due to this.

2 Answers 2

4

You don't need to create a JSON string, then parse it with JS: it's far more easily done with this:

var words = {},
    xyz = [1.5,2,2.1,2.4,2.5,3,3.5,3.8,3.9,4.5,4.8,5.2,5.3,5.3,6.5,7,7.2,8];

for (var i = 0, l = xyz.length/2; i < l; i++) {
  words['a' + (i + 1)] = { 
    s: xyz[2*i], 
    e: xyz[2*i + 1] 
  };
}

console.log(words);

Explanation: you go through your source arrays, taking each pair into an object literal and assign it to words object with bracket notation (so that value of 'a' + (i+1) is evaluated as a new key).

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

Comments

1

There's basically no reason to create a JSON string in a browser manually, instead create the object and then use JSON.stringify on it. (Most browsers have it by default, if not you can add a shim.) For instance:

var counter;
var words = {};
var xyz = [1.5,2,2.1,2.4,2.5,3,3.5,3.8,3.9,4.5,4.8,5.2,5.3,5.3,6.5,7,7.2,8];
var i;
counter = 0;
for (i = 0; i < xyz.length; i += 2) {
    ++counter;
    words["a" + counter] = {s: xyz[i], e: xyz[i + 1]};
}
console.log("words (before stringify):", words);
words = JSON.stringify(words);
console.log("words (after stringify):", words);

If you're going to create JSON manually, you need to learn and follow its rules. The keys must be in double quotes (so, "s": ... not s: ...), for instance.

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.