I'm trying to put json data into the codeigniter-restserver response, but the json code is put into double quotes effectively rendering it unreadable.
I'm trying to set the response like this currently:
$this->response(array(
'status' => $result['success'],
'error' => $result['cause'],
'result' => $result['result']
), $result['statuscode']);
Where $result['result'] is the json code.
Use the json_decode() to convert your json data in to array. Try it...
$this->response(array(
'status' => $result['success'],
'error' => $result['cause'],
'result' => json_decode($result['result'],true)
), $result['statuscode']);
Related
I'm working on a Laravel project that implements react-jsonschema-form and I need to convert the values saved in the database to an associative array so I can pluck certain values from it. However I am getting strange results when doing so.
Here is the code I use to grab the JSON data from the table and then convert to an array:
$form = Form::where('id', $formId)->get();
$converted = json_decode($form[0]->form_data, true);
$formArray = print_r($converted, 1);
return $formArray;
For testing purposes I am simply rendering the data in the browser.
The result from the above return is:
Array
(
[1] => Array
(
[1.1] => New
[1.2] => Ms
[1.3] => Isobel Fleming
[1.4] => Array
(
[uprn] => 52375918
[address_1] => Fake Street
[address_2] =>
[address_3] =>
[town_city] => BRISTOL
[postcode] => BS1 3KE
)
[1.5] => 0129711011
[1.6] => 0800999111
[1.7] => 0781100022
[1.8] => isobelfleming#jourrapide.com
)
)
which is great. However when I try and access anything from it like:
return $formData[1][1.1]
I get:
String offset cast occurred
If I try using a string:
return $formData[1]['1.1']
I get:
Illegal string offset '1.1'
So I am not sure what to do to access this data. The problem is, although it's not ideal to have the associate keys with decimals in them, this is the way the schema is set up and it's several thousand lines long - this is just a snippet of the form data.
Is there anything that can be done in order to get the data from this array?
I figured it out. It seems like the following line was the problem:
print_r($converted, 1);
It didn't need to be printed as an array, I should have just used the $converted variable to access the data like so:
return $converted[1]['1.1'];
I am trying to insert an entire api response into a MySQL table using Laravel Eloquent but I am getting 'Array to string conversion' error. How do I solve this?
Please note, it is compulsory that I save the entire API response.
My API call
$response = Curl::to($url.$request->account_number)
->withData($data)
->asJson(true)
->get();
My Query
TransactionLog::create([
'payer' => $request->payer,
'amount' => $request->amount,
'phone' => $request->phone,
'response' => $response
]);
Looks like you using ixudra/curl ?
With asJson(true) you will receive json_decode response, so if your plan is to save raw json response in the database you'll have to json_encode it like:
TransactionLog::create([
'payer' => $request->payer,
'amount' => $request->amount,
'phone' => $request->phone,
'response' => json_encode($response)
]);
I'm trying to use the model create option and this is my array:
$result = array(
'match_id' => $input['id'],
'score' => $input['score'],
'result' => $input['result'],
'headline' => NULL,
'article' => $input['report'],
'tries' => $input['try'],
'try_amount' => $input['tryquant'],
'conversions' => $input['conv'],
'conv_amount' => $input['convquant'],
'penalties' => $input['pens'],
'pen_amount' => $input['penquant'],
'dropgoals' => $input['dgs'],
'dg_amount' => $input['dgquant']
);
Result::create($result);
The contents of some of these are arrays themselves. eg:
$input['penquant'] = [
"4"
]
When I run my code, it saves the data to the DB simply as Array and throws up the following error:
ErrorException in helpers.php line 703: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
Can someone tell me what I'm doing wrong and how to fix it?
Shouldn't have rushed, forgot to use json_encode.
The best is to use mutators and accessors in your model.
example of mutator
// convert pen_amount from snake case to studly case
// The set...attribute (the ... is you field name which is in studly case) helps transform the data before you save it
// into the database
public function setPenAmountAttribute($value)
{
$this->attributes['pen_amount'] = serialize($value);
}
example of an accessor is
// convert pen_amount from snake case to studly case
// the get...Attribute (the ... is you field name which is in studly case) helps you convert the data back to it original state
public function getPenAmountAttribute($value)
{
return unserialize($value);
}
You can use accessors and mutators for all your fields that you want to save as array. This is elegant. No need to manually use json_encode and decode in your controllers.
When json response sends response.success == false, I can see the console log showing me the error, but x-editable seems that doesn't catch the return, and the value in the screen is changed to the new one I had introduced, although it has not been really saved. Is there something wrong?
Here is piece of the CGridView code I use:
'class' => 'editable.EditableColumn',
'editable' => array(
'model' => $model,
'params' => array('YII_CSRF_TOKEN' => Yii::app()->request->csrfToken),
'url' => $this->createUrl('user/update'),
'success' => 'js: function(response, newValue) {
if(!response.success)
console.log(response.msg);
return response.msg;
}',
'options' => array(
'ajaxOptions' => array('dataType' => 'json')
),
)
EDIT 1:
Ok, I have been working on that, and I have found which is the problem. It seems that the javascript function I put on success is not working properly.
The if statement is catching correctly the response, but the return value is not being sended correctly. I explain: if I put a literal like that: return "test return"; the value is returned correctly, but if I put return response.msg; nothing is sended.
Of course, response.msg is not empty and contains the String message correctly.
Ok, I have been working on that and I found my stupid mistake... I was returning msg as array and I had to do this:
return response.msg[index];
Where index is where the message is stored.
It was really embarrassing losing time with that...
I am trying to extract some data from an array with the following syntax:
#entries_from_db = XrEntry.find(:all, :conditions => [:FeedURI => uri ], :select => 'json')
The :FeedURI is the record that contains an array with uri's ["123456", "23345", "4453"]
The uri is the variable wich contains the current uri.
The statement I'm trying to make is 'select JSON from XrEntry where FeedURI contains uri'
Im stuck on the part to access the array and always get several error msg's when I'm trying different code.
Does anyone has an idea?
Thanks!
I solved it with this syntax
#entries_from_db = XrEntry.find(:all, :conditions => ["FeedURI like ?", "%#{uri}%"] , :select => 'json')
the "%#{your_rails_variable}%" is needed to read in an array
You seem to have switched the condition syntax. you chould start with the db attribute and then the variable.
#entries_from_db = XrEntry.find(:all,
:conditions => { :uri => FeedURI },
:select => 'json')
That will return an array of XrEntry objects with only the json attribute present. To get an array of only the json data you could map it like this:
#json_array = #entries_from_db.map(&:json)