how can convert URL encoded JSON sent from my android application into PHP array.Current format i am getting looks like below format.
[{\\\"product_id\\\":\\\"33\\\",\\\"amount\\\":\\\"1\\\"},{\\\"product_id\\\":\\\"34\\\",\\\"amount\\\":\\\"3\\\"},{\\\"product_id\\\":\\\"10\\\",\\\"amount\\\":\\\"1\\\"}]
How can i convert those data into below format
product_id amount
33 1
34 3
10 1
Because i want to insert those data into MySQL database.Can anyone please help me regarding this problem.
Use json_decode :
echo json_decode($jsonarr);
this can be done by json_decode
$json = '{"foo": 12345}';
$obj = json_decode($json);
print $obj->{'foo'}; // 12345
Good read
--- common mistakes using json_decode()
json_decode(jsonencoded string, TRUE) is correct way to encode json string.
But your json string encoded too deeper and recursive. your json encode string should as below
[{"product_id":9,"amount":500},{"product_id":9,"amount":500},{"product_id":9,"amount":500}]
Other wise, you will get NULL value
Related
I am using a astrology API which sends an json string as response to the query. But i have been trying for long to convert it into json and retrieve different items from the response string. Here is the example of the response:
{"ashtakoota":{"status":true,"received_points":26},"manglik":{"status":true,"male_percentage":13.25,"female_percentage":13.75},"rajju_dosha":{"status":false},"vedha_dosha":{"status":false},"conclusion":{"match_report":"Marriage between the prospective bride and groom is highly recommended. The couple would have a long-lasting relationship, which would be filled with happiness and affluence."}}
I am using php script so i tried the following code :
$json = json_decode($res1, true);
TRY 1 --> echo array_values($json[1]);
TRY 2 --> echo $json.ashtakoota.status;
TRY 3 --> echo $res1.ashtakoota.status;
But the output is always blank. I doubt that $json is empty or the json response is not perfectly json.
PHP uses string keys for its arrays, which is what json_decode(...) returns. As such, you need to access them as:
echo $json['ashtakoota']['status'];
Which should then output true for your example JSON input.
The true parameter on json_decode will cause it to return an array, not an object. Your syntax for objects is also incorrect, it's not a dot, but rather -> that you need.
$json = json_decode($res1);
echo $json->ashtakoota->status;
I have the following code that converts json into an array:
$str = file_get_contents('http://localhost/data.json');
$decodedstr = html_entity_decode($str);
$jarray = json_decode($decodedstr, true);
echo "<pre>";
print_r($jarray);
echo "</pre>";
but my $jarray keeps returning null... I dont know why this is happening.. i have already validated my json in this question:
validated json question could anyone tell me what i am doing wrong? or what is happening. Thanks in advance.
when i echo my $str i get the following:
You are passing to json_decode a string that is not valid JSON, this is the reason NULL is returned.
As I see from comments inspecting the error code generated gives 4 that corresponds to the constant JSON_ERROR_SYNTAX that just means the JSON string has a Syntax Error.
(See http://php.net/manual/en/function.json-last-error.php)
You should inspect (echo) what you get from
$str = file_get_contents('http://localhost/data.json');
(You may edit your answer and post it - or a portion of it)
For sure it is not valid JSON; the problem lies there: in data.json.
Then as you fix things and get from data.json what is expected I would ensure you really need to use html_entity_decode on the fetched data.
It would be "weird" to have html encoded JSON data.
UPDATE
Looking at what you get from data.json it seem the JSON data contains actually HTML entities (as I see the presence of s)
This is actually weird, the right thing to do would be to fix how data.json is generated ensuring non-html-encoded JSON data is returned, charset is UTF-8 and the response content type is Content-Type: application/json.
We can't deepen this here as I don't know where does data.json come from or the code that generates it. Eventually you may post another answer.
So here is a quick fix provided that the right approach would be what I just suggested above.
As you decode html entities, non breaking spaces turns into 2 byte UTF-8 characters (byte values 196, 160) that are not valid for JSON encoded data.
The idea is to remove these characters; your code becomes:
$str = file_get_contents('http://localhost/data.json');
$decodedstr = html_entity_decode($str);
// the character sequence for decoded HTML
$nbsp = html_entity_decode( " " );
// remove every occurrence of the character sequence
$decodedstr = str_replace( $nbsp, "", $decodedstr );
$jarray = json_decode($decodedstr, true);
from php manual
http://php.net/manual/en/function.json-decode.php
Return:
... NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit
So, surely the JSON string passed to json_decode() is not valid:
maybe because of html_entity_decode
I want to pass a JSON: {"name":"jason","age":"20} in PHP though POST
In RoR, I can get the two values by using params["name"] & params["age"]
But I don't know how to get them in PHP.
I understand that I can 'translate' the JSON string into associative array by using json_decode but I don't know how to get the JSON string.
In my PHP code, I has tried something like this:
<?php
$json_string = $_POST['params'];
$json_object= json_decode($json_string);
print_r($json_object);
echo $json_object->name;
echo " ";
echo $json_object->age;
?>
Then I has tested the PHP with terminal and I got the correct result
curl -d 'params={"name":"jason", "age":"20"}' xxxx/test_json_decode.php
It works but it seems strange to me, because I didn't set the 'Content-Type: application/json'
Is it the correct way to parse JSON in PHP?
The content-type is only useful in certain cases, such as jquery doing a standard .post where you haven't explicitly told it to expect a json response. A json string is just text, and the content-type is just a clue to the receiver. but you could still send a json string with image/jpeg and still decode it and get a native structure again.
As long as what you pass into json_decode() is a valid JSON string, regardless of the mime-type it was sent with, it'll be decoded into a native structure.
recently i used some JSON data in JQuery. now i want the same thing in PHP.
For Example:
MySQL query returns data like
$result='{"username":"john","age":"18", "birthdate":"19880221"}';
but when i echo this data in PHP, like:
echo $result.username;
echo $result.age;
it shows output:
{"username":"john","age":"18", "birthdate":"19880221"}.username
{"username":"john","age":"18", "birthdate":"19880221"}.age
but i want output this:
John
18
PHP is not Javascript, the . operator is for string concatenation and PHP has no native support for JSON syntax. You need to convert the JSON formatted data into an array and use array syntax:
$result = json_decode($result, true);
echo $result['username'];
echo $result['age'];
php is not js. you have to decode data first, using json_decode
if $result really contains the data you posted
Your result is actually just a string, formated like JSON. It's not an array in PHP. If U want to handle JSON output, you can use json_decode() first, and then get access to data via PHP array syntax like this:
$result = json_decode($result,true);
echo $result['some_key'];
I am storing this {background:"default.jpg"} in the database in field of tables as i am taking the table fields data and makint the json by json_encode while encoding this json also get encoded and it is not valid json so how should i encode these json.
{"id_session":"c72b0581e7675b596a7651a7bb906438","gibid":"54","name":"Market Place","type":"S","num_owners":"0","inner_template":"","inner_data":"{background:\"default.jpg\"}","outer_template":"","o
it is adding the slashes how should i get return the valid json.
thanks.
Don't store JSON in the database, store it in a neutral format, like key/value columns. Or:
Decode the JSON, merge it into the array to be encoded, then encode it.
$data = array('id' => ...);
$data['inner_data'] = json_decode($databaseJson, true);
json_encode($data);
So you have a JSON string in the database and then you get it out of it and do a json_ecnode on ir again? For php you are just encoding some string (thats why the backslashes on the quotations marks are coming from).
But to achieve what you actually want, you could to decode the JSON string from the database first and then encode it with the rest of your data again.