1

I have returned data from php (using json):

"[4, [{
    "quantity": "1",
    "name": "item 1",
    "price": "2",
    "currency": "GBP",
    "description": "item 1 description"
}, {
    "quantity": "1",
    "name": "item 1",
    "price": "2",
    "currency": "GBP",
    "description": "item 1 description"
}]]"

Then how do I access the data. It used to return use the second part:

    [{
        "quantity": "1",
        "name": "item 1",
        "price": "2",
        "currency": "GBP",
        "description": "item 1 description"
    }, {
        "quantity": "1",
        "name": "item 1",
        "price": "2",
        "currency": "GBP",
        "description": "item 1 description"
    }]

which I used jQuery.parseJson to turn into an object but I can't seem to figure out how to add in the second part the number 4

help would be great

my php code is like this

            $array['items'] = array();      
            $arrayOfMyNumbers = array();

            $total = 0;
            for( $i = 0; $i<2; $i++ ) {
                $foo = new StdClass();
                $foo->quantity = "1";
                $foo->name =  "item 1";
                $foo->price = "2";
                $foo->currency = "GBP";
                $foo->description = "item 1 description";;
                $arrayOfMyNumbers[] = $foo;
                $total += ($foo->price*$foo->quantity);
            }

            $returnArray = array();
            array_push($returnArray,$total,$arrayOfMyNumbers);

so I thought I'd be able to access that from javascript:

            jsonArrayResponse =  (jsonObj);
            if(typeReq =="button"){
            console.log("return is "+(jsonArrayResponse));

but it's how I get the 4 and then the second array part so I can convert it to an object.

Finally solve it!!!!

If you look at the original data you can see leading and trailing quotes. These were causing the json decode to fail. So I put in some regex and it work:

            success: function (jsonObj) {
            console.log(jsonObj);
            jsonArrayResponse =  (jsonObj);
            var someStr = jsonObj.data.replace(/^"(.*)"$/, '$1');
            console.log("some str is "+someStr);

            parsed = JSON.parse(someStr);
            console.log("this should be 4"+parsed[1]); 

definitely one of these ones where it's very easy to miss. Thanks to Devlin who helped me track it down.

0

3 Answers 3

1

If all you need to do is add the 4 (that's in the first part) to the second json object, you will just need to create a new array, add 4, and add the second json object:

var secondJsonObject = [{
        "quantity": "1",
        "name": "item 1",
        "price": "2",
        "currency": "GBP",
        "description": "item 1 description"
    }, {
        "quantity": "1",
        "name": "item 1",
        "price": "2",
        "currency": "GBP",
        "description": "item 1 description"
    }];

var newJsonObject = [4, secondJsonObject];
Sign up to request clarification or add additional context in comments.

6 Comments

I added some of the code. I already was trying this as two parts of an array - I think?
I guess I'm not really clear on what problem you're having, and what you are trying to do.
I'm creating an object in php (from a databbase) and then passing it back to javascript. Where I have the total amount - the two prices added together =4 and the objects themselves. This is then bundled together and sent to the payment system.
What does jsonObj look like?
jsonObj in console is data : "[4,[{"quantity":"1","name":"item 1","price":"2","currency":"GBP","description":"item 1 description"},{"quantity":"1","name":"item 1","price":"2","currency":"GBP","description":"item 1 description"}]]"
|
0

how do I access the data?

You'll still use JSON.parse().

var json = '[4, [{"quantity": "1","name": "item 1","price": "2","currency": "GBP","description": "item 1 description"}, {"quantity": "1","name": "item 1","price": "2","currency": "GBP","description": "item 1 description"}]]';

var parsed = JSON.parse(json);
console.log(parsed[0]);  //4
console.log(parsed[1][0].quantity);
console.log(parsed[1][1].quantity);

Or, put another way:

for (var i = 0; i < parsed.length; i++) {
  console.log(parsed[i]);  //4
  for (var j = 0; j < parsed[i].length; j++) {
    var obj = parsed[i][j];
    console.log(obj);
    console.log(obj.quantity);
  }
}

Demo: https://jsfiddle.net/zephyr_hex/2na2j317/


Update

OP states there is an error regarding "Unexpected token , in JSON at position 1". This can occur if the received response is not a string. JSON.stringify() will allow you to then JSON.parse().

var json2 = JSON.stringify([4, [{"quantity": "1","name": "item 1","price": "2","currency": "GBP","description": "item 1 description"}, {"quantity": "1","name": "item 1","price": "2","currency": "GBP","description": "item 1 description"}]]);

var parsed2 = JSON.parse(json2);

10 Comments

I tired this but I got Unexpected token o in JSON at position 1 which is why I'm here
@user1616338 : That's because your JSON string has line feeds in it. Put the JSON string on one line. You also need to wrap the string in single quotes, not double quotes. See my demo here: jsfiddle.net/zephyr_hex/2na2j317
I can't see where line feeds would have come from the code generates the string - what I'm showing is the console.log output?
@user1616338 : I just updated my question showing you the problem.
okay so I solve it - your idea of the validator gave me a clue. The whole return had quotes around it so it wan't being decoded correctly. Once I added a bit of regex to it to remove the leading and trailing quote it worked! Thanks you really helped me
|
0

Rough Pass:

$json_array = [];
$json_array[] = 4;
$json_array[] = $first_array;
$json_array[] = $second_array;
return json_encode($json_array);

Note: There is NO guarantee you'll get the array values/objects in the order you added them.

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.