Gal Appelbaum
Gal Appelbaum

Reputation: 1955

How to break down an array of objects within a string

I have some code that returns something like this:

body: '[
    {
        name: "name",
        lastname: "lastname"
    },
    {
        name: "name",
        lastname: "lastname"
    },
    {
        name: "name",
        lastname: "lastname"
    }
]'

Of course extracting the body is a simple object.body however, to get rid of the '' that wraps the array is just destroying me. I tried doing object.body.slice(1,-1) to get rid of them, it didnt work. I'm clearly not using the object properly.

How can I "extract" the array from within the body into a usable array?

Upvotes: 0

Views: 75

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386560

With a valid JSON string, you could just parse the string for an object with JSON.parse, if you have .

array = JSON.parse(string);

Upvotes: 0

Sh Ndrukaj
Sh Ndrukaj

Reputation: 84

You can use split function and then take the first element, let me say

var a = '[{name: "name",lastname: "lastname"},{name: "name",lastname: "lastname"},{name: "name",lastname: "lastname"}]';
    var s = a.split("'");

s[0] will return you the desired result

Upvotes: 0

spanky
spanky

Reputation: 2870

It sounds like you want to evaluate the content of the string. Assuming whatever code building this string can't actually build JS objects to begin with, you can use eval or Function to generate the objects you need.

var data = eval(string);

Note that you must be sure that the source of the string is safe and reliable, otherwise you could be evaluating malicious code. There may also be performance consequences to using eval.

Using Function is a tiny bit safer, only because the code can not access your local variables. It should also avoid the performance costs of eval.

var data = Function("return (" + string + ");")();

Same warning about malicious code though.


If the string data was valid JSON, you could use JSON.parse, but it isn't, so you can't. To avoid security issues, either have the source provide valid JSON data, or write your own minimal parser to parse the data.

Upvotes: 2

Related Questions