Как отформатировать ответ json из Twitter API для передачи в Watson Personality Insight

Я хотел использовать Personality Insight Service от Watson для анализа твитов пользователя. Я использую PHP для кодирования. Вот блок кода, который я использую, чтобы получить твиты из Twitter API и ввести их в службу PI Watson.

    //Watson PI Parameters
$pi_url = 'https://gateway.watsonplatform.net/personality-
insights/api/v3/profile?version=2016-10-20';
$pi_username = 'XXXX';
$pi_password = 'YYYY';
// auth parameters
$api_key = urlencode('API KEY'); // Consumer Key
$api_secret = urlencode('API Secret'); // Consumer Secret
$auth_url = 'https://api.twitter.com/oauth2/token';

// Twitter Data Parameters
$data_username = 'Screen Name'; // username
$data_count = 10; // number of tweets
$data_url = 'https://api.twitter.com/1.1/statuses/user_timeline.json?
tweet_mode=extended';

// get api access token
$api_credentials = base64_encode($api_key.':'.$api_secret);

$auth_headers = 'Authorization: Basic '.$api_credentials."\r\n".
'Content-Type: application/x-www-form-urlencoded;charset=UTF-
8'."\r\n";

$auth_context = stream_context_create(
array(
'http' => array(
'header' => $auth_headers,
'method' => 'POST',
'content'=> http_build_query(array('grant_type' =>
'client_credentials', )),
)
)
);

$auth_response = json_decode(file_get_contents($auth_url, 0,
$auth_context), true);

$auth_token = $auth_response['access_token'];

// get tweets
$data_context = stream_context_create( array( 'http' => array( 'header' =>
'Authorization: Bearer '.$auth_token."\r\n", ) ) );

$data = file_get_contents($data_url.'&count='.$data_count.
'&screen_name='.urlencode($data_username), 0, $data_context);
print_r($data);

// Pass $data as input to PI
$ch = curl_init();
// Sets the URL cURL will open
curl_setopt($ch, CURLOPT_URL, $pi_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
)
);
// Here's the HTTP auth
curl_setopt($ch, CURLOPT_USERPWD, $pi_username." : ".$pi_password);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, getcwd() . "\CertificateLocation");
// Makes curl_exec() return server response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// And here's the result JSON
$response = curl_exec($ch);
print curl_error($ch);
curl_close($ch);
print_r($response);

Я получаю {
«код»: 400,
«sub_code»: «S00005»,
«error»: «Неверный ввод JSON в строке 4, столбец 28»} ошибка.

Может кто-нибудь помочь, пожалуйста, как мне предварительно отформатировать мой ответ в Твиттере, чтобы PI мог идентифицировать его как входные данные Json и проанализировать его.

РЕДАКТИРОВАТЬ:

Добавление результата в твиттере в качестве ответа, так как он слишком длинный для комментариев. Вот результат, который я получаю с помощью твиттера Amazon (попробовал это только для теста)

    [{
"created_at": "Thu Apr 20 14:49:27 +0000 2017",
"id": 855070913997492225,
"id_str": "855070913997492225",
"full_text": "@realivanspeaks Aww! We love our customers like Buddy loves a his sugar. \ud83d\ude0d \ud83c\udf6c",
"truncated": false,
"display_text_range": [
16,
76
],
"entities": {
"hashtags": [
],
"symbols": [
],
"user_mentions": [
{
"screen_name": "realivanspeaks",
"name": "Ivan Speaks",
"id": 2484007045,
"id_str": "2484007045",
"indices": [
0,
15
]
}
],
"urls": [
]
},
"source": "\u003ca href=\"https:\/\/www.sprinklr.com\" rel=\"nofollow\"\u003eSprinklr\u003c\/a\u003e",
"in_reply_to_status_id": 855068504642514944,
"in_reply_to_status_id_str": "855068504642514944",
"in_reply_to_user_id": 2484007045,
"in_reply_to_user_id_str": "2484007045",
"in_reply_to_screen_name": "realivanspeaks",
"user": {
"id": 20793816,
"id_str": "20793816",
"name": "Amazon",
"screen_name": "amazon",
"location": "Seattle, Washington",
"description": "Official Twitter of http:\/\/t.co\/4rwjfdidk3. Contact @AmazonHelp for customer support.",
"url": "http:\/\/t.co\/Z2A4m7UeSv",
"entities": {
"url": {
"urls": [
{
"url": "http:\/\/t.co\/Z2A4m7UeSv",
"expanded_url": "http:\/\/www.amazon.com",
"display_url": "amazon.com",
"indices": [
0,
22
]
}
]
},
"description": {
"urls": [
{
"url": "http:\/\/t.co\/4rwjfdidk3",
"expanded_url": "http:\/\/Amazon.com",
"display_url": "Amazon.com",
"indices": [
20,
42
]
}
]
}
},
"protected": false,
"followers_count": 2567418,
"friends_count": 157,
"listed_count": 13988,
"created_at": "Fri Feb 13 18:39:54 +0000 2009",
"favourites_count": 3092,
"utc_offset": -25200,
"time_zone": "Pacific Time (US & Canada)",
"geo_enabled": true,
"verified": true,
"statuses_count": 23791,
"lang": "en",
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "9ACAF8",
"profile_background_image_url": "http:\/\/pbs.twimg.com\/profile_background_images\/448506280982753280\/GZ6eb7ux.png",
"profile_background_image_url_https": "https:\/\/pbs.twimg.com\/profile_background_images\/448506280982753280\/GZ6eb7ux.png",
"profile_background_tile": false,
"profile_image_url": "http:\/\/pbs.twimg.com\/profile_images\/786252488223580160\/9-Lwv1sI_normal.jpg",
"profile_image_url_https": "https:\/\/pbs.twimg.com\/profile_images\/786252488223580160\/9-Lwv1sI_normal.jpg",
"profile_banner_url": "https:\/\/pbs.twimg.com\/profile_banners\/20793816\/1492450739",
"profile_link_color": "FF9900",
"profile_sidebar_border_color": "FFFFFF",
"profile_sidebar_fill_color": "FFFFFF",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": null,
"follow_request_sent": null,
"notifications": null,
"translator_type": "none"},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 1,
"favorited": false,
"retweeted": false,
"lang": "en"}]

0

Решение

Задача ещё не решена.

Другие решения

Других решений пока нет …

По вопросам рекламы [email protected]