2

How I can parse 2 JSON objects? e.g

AJAX return just one Object appear's correctly.

Object {32 : "Joseph"} 

But, when return more than 2 objects, I've got this:

ResponseText:  "{"users":{"32":"Jospeh"}}{"users":{"48":"Jospeh K."}}"

I already trieD to parse with JSON.parse but returns an error: "Uncaught SyntaxError: Unexpected token {"

So, How I can parse to return something like this:?

 Object {32 : "Joseph"} 
 Object {48 : "Joseph K"} 

Instead of "responseText"

Considerations:

  1. If returns just ONE object, appears correctly in console(example);
  2. If returns more than TWO objects, appears responseText;
  3. AJAX dataType: JSON

I'll be very grateful if someone can help with this. =D

PHP:

public function get_error_message()
{

    $message = "";
    foreach ($this->errors as $value) {

        if ($value instanceof UsersError) {
            $message.= json_encode(array('errors' => array($value->getCode() => $value->getMessage())));

        }
    }

    return $message;
}
5
  • can you control the return of the json string? Commented Oct 15, 2015 at 3:18
  • that's invalid json ... need to fix server output. Can only have one outer set of braces ...either [] or {} for the full response Commented Oct 15, 2015 at 3:19
  • Indeed, it is not a valid JSON. It should be: [{"users":{"32":"Jospeh"}}, {"users":{"48":"Jospeh K."}}] ... and also this JSON does not make any sense at all. Commented Oct 15, 2015 at 3:20
  • JSON parsers expect a single (root) value. If you want to respond with multiple Objects, they should be as values within an Array or another Object. Otherwise, you'll need to determine a way to separate them first (dataType: 'text' to disable jQuery's parsing) so you can parse each Object individually ($.parseJSON()). Commented Oct 15, 2015 at 3:20
  • that PHP confirms it ... multiple json_encode (once per foreach iteration) - results in multiple concatenated JSON strings Commented Oct 15, 2015 at 3:31

4 Answers 4

2

The problem is in your PHP code. You can't simply concatenate JSON and think that it will be valid.

Instead of

$message = "";
foreach ($this->errors as $value) {

    if ($value instanceof UsersError) {
        $message.= json_encode(array('errors' => array($value->getCode() => $value->getMessage())));
    }
}

you should generate a proper PHP object, and then encode it to JSON once.
For example, in your case, it can be an array:

$errorsArray = array();
foreach ($this->errors as $value) {
    if ($value instanceof UsersError) {
        $errorsArray[] = array($value->getCode() => $value->getMessage());
    }
}

echo json_encode(array('errors' => $errorsArray));

Then, a result will be the following no matter how many objects it returns - none,

{
    "errors": []
}

only one or

{
    "errors": [
        {"32": "Joseph"}
    ]
}

many

{
    "errors": [
        {"32": "Joseph"},
        {"48": "Joseph K."}
    ]
}

In JavaScript you will be able to do:

$.ajax({}).done(function(data) {
    console.log(data.errors.length);
});

You can generate another JSON response which will be more convenient to work with in JavaScript. It's up to your requirements and fantasy.

For example, I would do a single associated array:

PHP:

$errorsArray = array();
foreach ($this->errors as $value) {
    if ($value instanceof UsersError) {
        $errorsArray[$value->getCode()] = $value->getMessage();
    }
}

echo json_encode(array('errors' => $errorsArray));

JSON:

{
    "errors": {
        "32": "Joseph",
        "48": "Joseph K."
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome! Works great. =) I only change the PHP code and worked. Thank you mate. u save my day!
0

That's not a valid JSON object. It is 2 JSON object in string representation concatenated together, which as far as I know is not valid. If you can't change the back-end, and you have to process this and can guarantee it is always 2 JSON object concatenated together, then you'll have to use string parsing to split them before sending them into JSON.parse(...) individually to get 2 JSON objects back.

Comments

0

this is not really standard way and your json is not valid:

but try this

str_data =  "{'users':{'32':'Jospeh'}}{'users':{'48':'Jospeh K.'}}";
str_data = str_data .replace("}{", "}}{{");
items = str_data .split("}{");
object_items = [];
for(i =0; i < items.length; i++){ object_items[i] = JSON.parse(items[i]); }

Comments

0

Your JSON is invalid, try push users into an array.

var obj =  {
    "users": [
        {
            "name": "Jospeh",
            "age": 32
        },
        {
            "name": "Joseph K",
            "age": 48
        }
    ]
 }

And for new users just push...

obj.users.push({ "name": "Neil A.", "age": 72 });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.