Cannot parse mutiple json rows in javascript - javascript

I am using twitterapi to get the friends list in php and I have encoded the result as a json array, but I cannot parse the json array in javascript.I have validated the json array produced by the php and its a valid json array. Below is my code.
php
$friends = array();
$friend_list = array();
$myfriend = array();
$connection = new TwitterOAuth($CONSUMER_KEY, $CONSUMER_SECRET,oauth_token,oauth_token_secret);
$friends =$connection->get("https://api.twitter.com/1.1/friends/list.json?cursor=-1&screen_name=twitterapi&skip_status=true&include_user_entities=false&count=200);
foreach($friends as $friend) {
if(!empty($friend))
{
foreach($friend as $value)
{
$friend_list['id']=$value->id;
$friend_list['screen_name']= $value->screen_name;
$friend_list['name']= $value->name;
$friend_list['profile_image_url']= $value->profile_image_url;
$friend_list['location']= $value->location;
array_push($myfriend, $friend_list);
}
}
}
$newarray = json_encode($myfriend);
'
javascript
<script>
var obj1 = JSON.parse('<?php echo $newarray ;?>');
console.log(obj1); // am not getting anything in console
</script>
EDITED
output from echo $newarray;
[
{
"id": 50393960,
"screen_name": "BillGates",
"name": "Bill Gates",
"profile_image_url": "http://pbs.twimg.com/profile_images/1884069342/BGtwitter_normal.JPG",
"location": "Seattle, WA"
},
{
"id": 141527741,
"screen_name": "prakashraaj",
"name": "Prakash Raj",
"profile_image_url": "http://pbs.twimg.com/profile_images/2951815972/ab32fb806b480d0dc761805ae4ef9775_normal.jpeg",
"location": "india"
},
{
"id": 88856792,
"screen_name": "aamir_khan",
"name": "Aamir Khan",
"profile_image_url": "http://pbs.twimg.com/profile_images/2254031972/_MG_2190_normal.jpeg",
"location": "Mumbai"
},
{
"id": 107318424,
"screen_name": "bipsluvurself",
"name": "Bipasha Basu",
"profile_image_url": "http://pbs.twimg.com/profile_images/419745345178832896/8JvqwEM9_normal.jpeg",
"location": "Mumbai, India"
}
]
Please help, am stuck with this

You can directly output the json:
Change to:
var obj1 = <?php echo $newarray ;?>;
For example:
<?php
$newarray = json_encode(array('name' => 'srain'));
?>
var obj1 = <?php echo $newarray ;?>;
It will output:
var obj1 = {"name":"srain"};
update
If your js script is not in the same file with the php code, the $newarray will be null.

In the absence of information about how you validated json array, this is what I can recommend. Change your javascript to:
<script>
var jsonString = '<?php echo $newarray ;?>';
console.log(jsonString);
var obj1 = JSON.parse(jsonString);
console.log(obj1); // am not getting anything in console
</script>
You can see the content of jsonString in the javascript console. That should give you hints about what is going wrong.
Note:You are fetching JSON content from twitter, converting it to PHP data structure and converting it back to JSON. Sending the JSON string from twitter to javascript is far more efficient - if there is no need to filter/alter the twitter returned data.

Related

PHP Javascript - Array multidimensional error

In practice, I create an array in PHP that then I pass to a JavaScript function.
So far so good. The array that the functions recieves is the following:
[[{"firstname": "Micheal", "lastname": "Brown"}], [{"car": "Ford", "model": "Fiesta"}]]
My problem is to get all the first array, that is this: {"firstname": "Micheal", "lastname": "Brown"}
and also the second array this: {"car": "Ford", "model": "Fiesta"}
I tried with alert (array [0]) but it only shows me this [
How can I do this?
I'll explain:
this is my php file:
class UserClasses
{
public $firstname;
public $lastname;
}
class CarClasses
{
public $car;
public $model;
}
if(isset($_POST['name'])){
populate($_POST['name']);
}
function populate(){
//I abbreviated the function for simplicity
$arrayUser = array();
$arrayCar = array();
$user = new UserClasses();
$user->firstname = "Micheal";
$user->lastname = "Brown";
array_push($arrayUser, $user);
$car = new CarClasses();
$car->car = "Ford";
$car->model = "Fiesta";
array_push($arrayCar, $car);
$arrayFinal = array($arrayUser, $arrayCar);
print json_encode($arrayFinal);
}
and this is the function in javascript:
//Ajax for calling php function
$.post('Classes.php', { name: name }, function(data){
var array = JSON.parse(data);
var arrayT = array[0];
alert(arrayT);
});
Here's what is happening with your code: you're accessing the first element of a JSON string, so my guess is you will get its first character: [.
You need to convert your string into an actual array before accessing it!
Use JSON.parse:
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.
- MDN web docs
For example you can do:
const json = '[[{"firstname": "Micheal", "lastname": "Brown"}], [{"car": "Ford", "model": "Fiesta"}]]'
// that's what you have
console.log(json[0])
// that's what you want
array = JSON.parse(json)
console.log(array[0])
First of all, if you are using json_encode to pass PHP array to JS, it encodes it to a JSON string. You have to parse it using JSON.parse() and only then the json string is transformed to regular array which you can use.
You can parse data and use it:
var arr = '<?php echo '[[{"firstname": "Micheal", "lastname": "Brown"}], [{"car": "Ford", "model": "Fiesta"}]]'; ?>';
var parsedarr = JSON.parse(arr);
for(var i=0;i<parsedarr.length;i++){
console.log(parsedarr[i][0]);
}
You are dealing with 3 different Data Types:
a PHP Multidimensional Array
a JSON String
a Javascript Object
Each needs to be converted into the next.
A PHP Array is converted into a JSON String, via json_encode() (in PHP)
A JSON String is converted into a Javascript Object, via JSON.parse() (in Javascript)
Now you have a Javascript Object which you can interrogate and manipulate using Javascript.
PHP Multidimensional Array:
$My_PHP_Array = array(
array(
'firstname' => 'Michael'
'lastname' => 'Brown'
),
array(
'car' => 'Ford'
'model' => 'Fiesta'
)
);
Convert PHP Multidimensional Array to JSON String:
json_encode($My_PHP_Array);
JSON String:
'{
[
[{
"firstname": "Micheal",
"lastname": "Brown"
}],
[{
"car": "Ford",
"model": "Fiesta"
}]
]
}'
Convert JSON String to Javascript Object:
var myJavascriptObject = JSON.parse(myJSONString);
Javascript Object:
myJavascriptObject = {
[
[{
"firstname": "Micheal",
"lastname": "Brown"
}],
[{
"car": "Ford",
"model": "Fiesta"
}]
]
};

How to covert JSON data into an array to plot a chart?

I've a php query which creates the JSON data of the the data received from the SQL query that is run. The JSON data is created using this query using this query
echo json_encode($res->fetch_all(MYSQLI_ASSOC), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT );
Now I want to plot a chart using fusionchart for which I need to convert this data into an array. I tried a sample JS code to convert the JSON data into an JS array and it worked
var data = { "timestamp": "2016-09-23", "value1": "0", "value2": "0", ........., "value49": "0", "value50": "0" };
var arr = [];
for (elem in data) {
arr.push(data[elem]);
}
console.log(arr);
Now in the data variable I need to pass the data from php code. This is just one of the records that I entered manually. There are over a million records and I need to convert all of them. How I do this?
You can use parseJSON() function :
var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );
You can just use Object.values() function to acquire values from an object.
var data = { "timestamp": "2016-09-23", "value1": "0", "value2": "0", "value49": "0", "value50": "0" };
var arr = Object.values(data);
console.log(arr);
For PHP
You can send only values and omit keys in PHP using following code. json_decode converts JSON string to an array. implode converts an array to a string.
<?php
$str = '{ "timestamp": "2016-09-23", "value1": "val1",
"value2": "val2", "value49": "val49", "value50": "val50" }';
$myJSON = json_decode($str, true);
echo '[' . implode(",", $myJSON) . ']';
Results:
[2016-09-23,val1,val2,val49,val50]

Unable to read properly from JSON file with php

I am trying to read from a JSON file into a PHP array and then echo the array's content, so I can fetch the info with ajax in javascript and convert the array in javascript to an array of JSON objects.
Here is how my JSON file looks like.
[["{\"id\":1474541876849,\"name\":\"D\",\"price\":\"12\"}"],["{\"id\":1474541880521,\"name\":\"DD\",\"price\":\"12\"}"],["{\"id\":1474541897705,\"name\":\"DDDGG\",\"price\":\"124\"}"],["{\"id\":1474541901141,\"name\":\"FAF\",\"price\":\"124\"}"],["{\"id\":1474543958238,\"name\":\"tset\",\"price\":\"6\"}"]]
Here is my php :
<?php
$string = file_get_contents("products.json");
$json_a = json_decode($string, true);
$arr = array();
foreach ($json_a as $key) {
array_push($arr,$key[0]);
}
foreach ($arr as $key) {
echo $key;
}
?>
And this is what I am getting on the client side :
{"id":1474541876849,"name":"D","price":"12"}{"id":1474541880521,"name":"DD","price":"12"}{"id":1474541897705,"name":"DDDGG","price":"124"}{"id":1474541901141,"name":"FAF","price":"124"}{"id":1474543958238,"name":"tset","price":"6"}
It looks like I am not that far, but what can I do so I can actually make this a JSON object?
Please help!
The problem is that you have JSON inside JSON.
you have to decode twice:
<?php
$string = file_get_contents("products.json");
$json_a = json_decode($string, true); //here you turn a JSON-string into an array containing JSON-strings
$arr = array();
foreach ($json_a as $key) {
array_push($arr,json_decode($key[0],true)); //and here you turn each of those JSON-strings into objects themselves
}
echo json_encode($arr);
gives me this:
[{
"id": 1474541876849,
"name": "D",
"price": "12"
}, {
"id": 1474541880521,
"name": "DD",
"price": "12"
}, {
"id": 1474541897705,
"name": "DDDGG",
"price": "124"
}, {
"id": 1474541901141,
"name": "FAF",
"price": "124"
}, {
"id": 1474543958238,
"name": "tset",
"price": "6"
}]
which is valid JSON itself and probably what you want.

how to decode nested json in php

i am having a json string like:
[
{
"message": "Test+sms",
"sender": "test",
"billcredit": "0.00",
"messageStatus": "DND",
"sendondate": "2015-04-22 15:22:00",
"provider": "aaaa"
},
{
"message": "Test+sms",
"sender": "test",
"billcredit": "0.00",
"messageStatus": "DND",
"sendondate": "2015-04-22 15:22:00",
"provider": "aaa"
},
{
"message": "Test+sms",
"sender": "test",
"billcredit": "1.00",
"messageStatus": "DELIVRD",
"sendondate": "2015-04-22 15:22:00",
"provider": "aaaa"
},
{
"message": "Test+sms",
"sender": "test",
"billcredit": "1.00",
"messageStatus": "DND REJECTED",
"sendondate": "2015-04-22 15:22:00",
"provider": "aaaa"
}
]
I try doing like this:
$objs = json_decode($data,true);
foreach ($objs as $obj){
$repor= $obj['messageStatus'];
echo $repor;
But its not working. Please anybody can help me to get rid out of this. Please help me to upload $repor sequentially in mysql.
Working Fine Now Check
$data='[{"message":"Test+sms","sender":"EXECUT","billcredit":"0.00","messageStatus":"DND","sendondate":"2015-04-22 15:22:00","provider":"aaaa"},{"message":"Test+sms","sender":"EXECUT","billcredit":"0.00","messageStatus":"DND","sendondate":"2015-04-22 15:22:00","provider":"aaa"},{"message":"Test+sms","sender":"EXECUT","billcredit":"1.00","messageStatus":"DELIVRD","sendondate":"2015-04-22 15:22:00","provider":"aaaa"},{"message":"Test+sms","sender":"EXECUT","billcredit":"1.00","messageStatus":"DND REJECTED","sendondate":"2015-04-22 15:22:00","provider":"aaaa"}]';
$objs = json_decode($data, true);
foreach ($objs as $obj){
$repor= $obj['messageStatus'];
echo $repor." ";
}
I have placed only single quotation around json array. Nothing more.
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[] = $row;
}
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Records'] = $rows;
print json_encode($jTableResult);
Looks like it's almost json, but not quite.
Try this:
$data = '{"messages":' . $data . '}';
$decoded = json_decode($data, true);
foreach ($decoded['messages'] as $message) {
$messageStatus = $message['messageStatus'];
echo $messageStatus;
}

Valid JSON to display data in angularJs

I want to display data(json) in my site using AngularJs . here's what i did :
Create a database in phpmyAdmin .
Create a table with 2 row , subject and body . Should i create an id ?
After doing with PHP and angular , I got JSON like this :
[{
"0":"Soheil","subject":"Soheil",
"1":"Sadeghbayan","body":"Sadeghbayan"}
,{"0":"","subject":"","1":"","body":""}
,{"0":"","subject":"","1":"","body":""}
,{"0":"dasdasd","subject":"dasdasd","1":"qe","body":"qe"}
,{"0":"Hello","subject":"Hello","1":"This is chandler !","body":"This is chandler !"}
,{"0":"","subject":"","1":"","body":""},
{"0":"Something new in website","subject":"Something new in website","1":"oh Awsome !","body":"oh Awsome !"
}]
I think this is invalid JSON because when I replace it with custom JSON that I wrote it work .
Json valid
{
"fruits": [
{
"id": "1",
"name": "Apple"
},
{
"id": "2",
"name": "Orange"
}
]
}
AngularJS
var fruitsApp = angular.module('fruitsApp', []);
fruitsApp.factory('fruitsFactory', function($http) {
return {
getFruitsAsync: function(callback) {
$http.get('fruits.json').success(callback);
}
};
});
fruitsApp.controller('fruitsController', function($scope, fruitsFactory) {
fruitsFactory.getFruitsAsync(function(results) {
console.log('fruitsController async returned value');
$scope.fruits = results.fruits;
});
});
Html
<ul>
<li ng-repeat="fruit in fruits">
{{fruit.subject}} is {{fruit.body}}
</li>
</ul>
php
include('config.php');
$data = json_decode(file_get_contents("php://input"));
$subject = mysql_real_escape_string($data->subject);
$body = mysql_real_escape_string($data->body);
mysql_select_db("angular") or die(mysql_error());
mysql_query("INSERT INTO newstory (subject,body) VALUES ('$subject', '$body')");
Print "Your information has been successfully added to the database.";
$query = "SELECT * FROM newstory";
$result = mysql_query($query);
$arr = array();
while ($row = mysql_fetch_array($result)) {
$subject = $row['subject'];
$body = $row['body'];
$arr[] = $row;
}
echo json_encode($arr);
Any idea ? Thx in advance
Your JSON is a valid. Refer to this for information on JSON and this to check/validate a JSON object.
The data coming back from your $http.get / database data does not have a fruits attribute and you expect that when you set your $scope.fruits (the below snippet is taken from your code):
$scope.fruits = results.fruits;
The structure of the data that is being returned by the $http.get call is different than the format of your sample data.
Here's your $http.get / database data (I shortened it for brevity):
[
{
"0": "Soheil",
"1": "Sadeghbayan",
"subject": "Soheil",
"body": "Sadeghbayan"
},
{
"0": "Hello",
"1": "This is chandler !",
"subject": "Hello",
"body": "This is chandler !"
},
{
"0": "",
"1": "",
"subject": "",
"body": ""
}
]
And here's your sample / mock data:
{
"fruits": [
{
"id": "1",
"name": "Apple"
},
{
"id": "2",
"name": "Orange"
}
]
}
The former is an array of objects with keys: 0, 1, subject and body.
The latter is an object with keys: fruits.
They are both valid JSON objects with different object structures. But, you expect a fruits attribute where there isn't one. Also, your HTML/UI might be expecting the data format to look like what is in your mock data. So check that too.

Categories

Resources