user1258134
user1258134

Reputation: 31

how to split some json arrays in one variable into different variables? (Javascript)

I'm confused about JSON.

I got this JSON data (already parsed) from php;

    var json =
    {"id":"1", "name":"AAA", "sex":"m", "age":"20", "region":"X"}
    {"id":"2", "name":"BBB", "sex":"m", "age":"25", "region":"Y"}
    {"id":"3", "name":"CCC", "sex":"f", "age":"30", "region":"Z"}
    {"id":"4", "name":"DDD", "sex":"m", "age":"35", "region":"Q"}

and these are separated arrays within one var.

I'd like to make them like this,

    var json1 = {"id":"1", "name":"AAA", "sex":"m", "age":"20", "region":"X"}
    var json2 = {"id":"2", "name":"BBB", "sex":"m", "age":"25", "region":"Y"}
    var json3 = {"id":"3", "name":"CCC", "sex":"f", "age":"30", "region":"Z"}
    var json4 = {"id":"4", "name":"DDD", "sex":"m", "age":"35", "region":"Q"}

I'm currently developing Titanium mobile (iOS) with PHP. and PHP send JSON data like this;

    foreach($responses as $response)
    {
        echo encode_json($response);
    }

※$responses is result from sql order.

and now Titanium side, Titanium file will receive and parse it.

    Req.onload = function()
    {
        var json = JSON.stringify(this.responseText);
        var response = JSON.parse(json);
        Ti.API.info(response);
    }

Ti.API.info says on console;

    [INFO] {"id":"1", "name":"AAA", "sex":"m", "age":"20", "region":"X"}{"id":"2", "name":"BBB", "sex":"m", "age":"25", "region":"Y"}{"id":"3", "name":"CCC", "sex":"f", "age":"30", "region":"Z"}{"id":"4", "name":"DDD", "sex":"m", "age":"35", "region":"Q"}
    //as I wrote it above

I'm sorry for those came to see JS problem but Titanium.

Upvotes: 0

Views: 11320

Answers (2)

gion_13
gion_13

Reputation: 41533

If your first json is actually an array like this :

var json = [
    {"id":"1", "name":"AAA", "sex":"m", "age":"20", "region":"X"},
    {"id":"2", "name":"BBB", "sex":"m", "age":"25", "region":"Y"},
    {"id":"3", "name":"CCC", "sex":"f", "age":"30", "region":"Z"},
    {"id":"4", "name":"DDD", "sex":"m", "age":"35", "region":"Q"}
];

Then you could split the array into individual variables like this :

for(var i=0,l=json.length;i<l;i++)
    window['json' + (i+1)] = json[i];

Note that declaring a variable in the global scope (like var foo = 'bar') can be done by attaching that name to the window object (window['foo'] = 'bar';);

Upvotes: 3

Rick Hoving
Rick Hoving

Reputation: 3575

Do you mean something like this?:

var json =
    {"id":"1", "name":"AAA", "sex":"m", "age":"20", "region":"X"}
    {"id":"2", "name":"BBB", "sex":"m", "age":"25", "region":"Y"}
    {"id":"3", "name":"CCC", "sex":"f", "age":"30", "region":"Z"}
    {"id":"4", "name":"DDD", "sex":"m", "age":"35", "region":"Q"}

var json1 = json[0];
var json2 = json[1];
var json3 = json[2];
var json4 = json[3];

Upvotes: 3

Related Questions