【问题标题】:Laravel: I cannot access to object property in nested json [duplicate]Laravel:我无法访问嵌套 json 中的对象属性 [重复]
【发布时间】:2019-04-04 15:05:10
【问题描述】:

我正在使用 angular 和 laravel,我的请求中有这个 json,但由于某种原因,我无法访问名为“llave_criptografica”的键中的数据,这是完整的 json

{username: "eeded", contrasena: null, llave_criptografica: {…}, clave_criptografica: null}

“llave_criptografica”里面的数据是这样的

{filename: "011503046233.p12", filetype: "application/x-pkcs12", value: "MIIaPAIBAzCCGfYG-base-64-encode"}

如您所见,我刚刚使用 base64 编码并发送了一个密钥,但是当我尝试访问它时,我收到了这个错误

        return $request->llave_criptografica->filename;

试图获取非对象的属性

如果我尝试作为数组访问,这是错误

        return $request->llave_criptografica["filename"];

JSON.parse 中位置 1 处的 JSON 中的意外数字

这是我存储文件数据的函数

onFileChange(event) {
let reader = new FileReader();
if(event.target.files && event.target.files.length > 0) {
  let file = event.target.files[0];
  reader.readAsDataURL(file);
  reader.onload = () => {
    this.formCertificado.get('llave_criptografica').setValue({
      filename: file.name,
      filetype: file.type,
      value: reader.result.split(',')[1]
    })

        }
  }
}

我做日志的时候,这是key的内容

array ( 'username' => 'eded', 'contrasena' => NULL, 'llave_criptografica' => array ( 'filename' => '011503046233.p12', 'filetype' => 'application/x-pkcs12', 'value' => 'MIIaP-base-64', ), 'clave_criptografica' => NULL, )

【问题讨论】:

  • var_dump($request-> llave_criptografica); 能得到什么?如果是另一个 json,则需要对其进行解码。
  • 您在此处复制的示例不是有效的 JSON,例如键不在引号内。如果您可以发布确切的请求正文会很有帮助。
  • 嗨,当我尝试解码时出现此错误,json_decode() 期望参数 1 为字符串,给定数组
  • 请发送dd($request->all()) 并编辑问题以包含该转储数据。
  • 所以llave_criptografica是一个数组,所以你需要用PHP中的数组方法来访问它,而不是对象。请注意,您的错误消息是两个不同的错误:Trying to get property of non-object 来自 PHP,并通过正确访问它来修复。 Unexpected number in JSON at position 1 at JSON.parse 是一个 javascript 错误,可能是因为您返回的是字符串,而不是 json。

标签: php json angular laravel


【解决方案1】:

要访问数据,您必须将其作为数组访问,使用 [] 与使用 -> 的对象相对。你可以这样做:

$request["llave_criptografica"]["filename"]; 

如果您需要像访问对象一样访问它,您始终可以将其转换为对象。

【讨论】:

  • 几乎; $request->llave_criptografica(或$request['llave_criptografica'])是可以的,但$request->llave_criptografica->filename不是,而$request->llave_criptografica['filename']是(或应该是)。
猜你喜欢
  • 2020-08-09
  • 2011-11-05
  • 1970-01-01
  • 1970-01-01
  • 2020-07-14
  • 1970-01-01
  • 2012-11-12
  • 2017-05-16
  • 2018-10-29
相关资源
最近更新 更多