Jump to content

How To Wrap A Json Array Inside A Json Object?


anevins

Recommended Posts

Hello,

 

I'm trying to wrap a JSON array inside a JSON object but cannot figure out how.

 

Here's the tutorial I'm following:

 

In this example, you send a JSON array inside a JSON object's "data" field. Each item should have a field called "text".

 

 

{"data": [{"text": "I love Titanic."},

{"text": "I hate Titanic."}]}

 

 

This is my JSON array (var_dumped)

string '["data",{"text":"Wrapped in my blanket always makes me feel a little better when I'm not feeling to well"},{"text":"@sportsology I know they are still far apart but I'm definitely feeling better"},{"text":"The way I'm feeling right now <<<<<"},{"text":"Sometimes my dad will sense when I'm feeling a bit shit and just give me a hug and it always makes me feel better. #appreciationtweet"},{"text":"@HayliMarie3 o no!!!!! I'm just now feeling better today!!! Suck down those emergencies!!!"},{"text'... (length=1005)

 

This is my JSON object (var_dumped)

string '"data"' (length=6)

 

How can I go about this?

My code is

function get140Sentiment ( $tweets ) {
$url = "";
// $content = file_get_contents($url);
$item_type = "data";
$text_array = array( $item_type );

foreach ( $tweets as $tweet ) {
$text['text'] = $tweet->tweet_text;
array_push($text_array, $text);
}

$json_object = "";
$json_object = json_encode ( $item_type, JSON_FORCE_OBJECT);
$json_array = json_encode( $text_array );

var_dump($json_object, $json_array);

}

What...what are you wanting these items to be? As far as I can tell, json_object will be an object that just contains the string "data". This matches your output (but not what you say you want). json_array will be an array of all the twitter posts you're fetching from somwhere. This, again, matches your output.

 

You probably want...

 

 

function get140Sentiment ( $tweets ) {

 $item_type = "data";
 $data = array('data' => array());

 foreach ( $tweets as $tweet ) {
   $data['data'][] = array('text'=> $tweet->tweet_text);
 }

 $json_object = json_encode ( $data, JSON_FORCE_OBJECT);
 $json_array = json_encode( $data );

 var_dump($json_object, $json_array);

}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.