#php #laravel
#php #laravel
Вопрос:
Я использую json_encode для преобразования массива в JSON и последующего сохранения в таблице MySQL. При попытке выполнить json_decode для данных из таблицы MySQL я получаю сообщение об ошибке, что аргумент, переданный в json_decode, является объектом.
«
json_decode()
ожидает, что параметр 1 будет строкой, заданный объект»
Вот строка JSON, хранящаяся в таблице MySQL:
{
"CreditScoreFactor":"{"98":" Make all future payments on time. The impact on your credit score from the bankruptcy will diminish over time.","negative_factors":[" There is a bankruptcy on your credit report"," The balances on your accounts are too high compared to loan amounts"," Lack of sufficient relevant real estate account information"," You have either very few loans or too many loans with recent delinquencies"],"04":" Paying down the balances on your accounts will benefit your score.","63":" Maintaining open and active credit accounts in good standing can help improve your credit score.","08":" Paying bills on time every month is important to maintaining a good credit score. If you remain behind with any payments, bring them current as soon as possible, and then make future payments on time. Over time, this will have a positive impact on your score."}",
"TotalBalances":"5039",
"TotalMonthlyPayments":"57",
"TotalAccounts":"4",
"OpenAccounts":"3",
"CloseAccounts":"1",
"DelinquentAccounts":"0",
"DerogatoryAccounts":"3",
"PublicRecords":null,
"Utilization":null,
"OnTimePaymentPercentage":null,
"BorrowerName":[
{
"first":"SOOR",
"middle":"R",
"last":"DOOR",
"InquiryDate":"2019-03-06"
}
],
"BorrowerBirth":[
{
"date":null,
"InquiryDate":[
"2019-03-06"
]
}
],
"previousAddresses":[
{
"dateReported":"2006-09-28",
"InquiryDate":[
"2019-03-06"
],
"address":{
"city":"SCOTTSDALE",
"direction":"N",
"houseNumber":"1001",
"postDirection":"",
"streetName":"27",
"stateCode":"AK",
"streetType":"PL",
"unit":"105",
"postalCode":"85257",
"type":"previous"
}
},
{
"dateReported":null,
"InquiryDate":[
"2019-03-06"
],
"address":{
"city":"PHOENIX",
"direction":"E",
"houseNumber":"4202",
"postDirection":"",
"streetName":"CACTUS",
"stateCode":"AZ",
"streetType":"RD",
"unit":"4101",
"postalCode":"85032",
"type":"previous"
}
},
{
"dateReported":"2007-10-09",
"InquiryDate":[
"2019-03-06"
],
"address":{
"city":"CALIFORNIA",
"direction":"N",
"houseNumber":"767",
"postDirection":"",
"streetName":"DAVID",
"stateCode":"AZ",
"streetType":"CT",
"unit":"",
"postalCode":"85226",
"type":"current"
}
}
],
"employer":[
{
"emp_updatedon":"2017-12-22",
"emp_name":"PROEM PARTY EVENT RENTALS",
"emp_partition":"0"
},
{
"emp_updatedon":"2007-04-27",
"emp_name":"PROFESSIONAL EVENT MNGMNT",
"emp_partition":"1"
}
]
}
Я заметил, что если я удалю обратную косую черту, ошибка исчезнет.
Кроме того, если я заключу значение базы данных в двойные кавычки, ошибка исчезнет.
Не уверен, в чем проблема. Нужно ли заключать json_encode()
данные в кавычки перед сохранением их в базе данных?
Использование Laravel 5.7 с php 7.3.2
ОБНОВЛЕНИЕ: Вот код, который преобразует массив в json
$reportData->extrainfo = !empty($report['extrainfo']) ? json_encode($report['extrainfo'],JSON_UNESCAPED_SLASHES) : null;
$reportData->save();
И вот код для восстановления значения DB:
if ($extrainfo = $this->extrainfo) {
$extrainfo = json_decode($extrainfo, true);
}
Комментарии:
1. где находится код для
While trying to do a json_decode on the data from mysql table
и"json_decode() expects parameter 1 to be string, object given"
этого? Или любой код.2. вам нужно сделать это
json_decode($json,true)
, при значении TRUE возвращаемые объекты будут преобразованы в ассоциативные массивы.3. @nullpoiяteя — сначала я так и подумал, но
I get an error that the argument passed to json_decode is an object
вероятно, это база данных возвращает объекты стандартного класса. Но без кода невозможно определить.trying to do a json_decode on the data from mysql table
4. Похоже на остатки двойного кодирования. И ошибка обычно указывает на то, что Eloquent уже неявно декодировал ciolumn в соответствии с объявлением JSON. (Здесь, конечно, показан недостаточный код.)
5. @ArtisticPhoenix Добавил код, который преобразует массив в json