Flutter 使用双引号将字符串转换为 Json

软体动物

在一个项目中,我得到一个字符串,我想转换为正确的 json。我有测试json.encode()但没有工作。

谢谢,

字符串不是 json:

{id: 2, status: 2, pseudo: giles, password: lmstvixKUKcmEKL, email: [email protected], phone: 710-934-8381, birthday: 2022-03-26, resume: Velit unde maiores nostrum sit et voluptate perspiciatis repellat., avatar_path: avatar_8.png, active: 0, created_at: 2022-05-26 13:40:31, updated_at: 2022-05-28 13:04:44, age: 0, avatar: http://localhost/api_alligatorsdujeu/storage/app/gallery/avatars/avatar_8.png, family: {id: 8, name: TREMBLAY, newsletter: false, philibert: true, active: true, created_at: 2022-05-26 10:18:15.000, updated_at: 2022-05-26 10:18:15.000}}

字符串 json :

{"id": 2, "status": 2, "pseudo": "giles", "password": "lmstvixKUKcmEKL", "email": "[email protected]", "phone": "710-934-8381", "birthday": "2022-03-26", "resume": "Velit unde maiores nostrum sit et voluptate perspiciatis repellat.", "avatar_path": "avatar_8.png", "active": 0, "created_at": "2022-05-26 13:40:31", "updated_at": "2022-05-28 13:04:44", "age": 0, "avatar": "http://localhost/api_alligatorsdujeu/storage/app/gallery/avatars/avatar_8.png", "family": {"id": 8, "name": "TREMBLAY", "newsletter": false, "philibert": true, "active": true, "created_at": "2022-05-26 10:18:15.000", "updated_at": "2022-05-26 10:18:15.000"}}
头脑

您正在尝试将字符串转换为与 json 语法不匹配的 json,因此任何使用常用 json 方法的尝试都将失败。

你的小把戏很好,但我建议使用像这样的正则表达式:

import 'dart:convert';

void main() {
    String notJson = '{id: 2, status: 2, pseudo: giles, password: lmstvixKUKcmEKL, email: [email protected], phone: 710-934-8381, birthday: 2022-03-26, resume: Velit unde maiores nostrum sit et voluptate perspiciatis repellat., avatar_path: avatar_8.png, active: 0, created_at: 2022-05-26 13:40:31, updated_at: 2022-05-28 13:04:44, age: 0, avatar: http://localhost/api_alligatorsdujeu/storage/app/gallery/avatars/avatar_8.png, family: {id: 8, name: TREMBLAY, newsletter: false, philibert: true, active: true, created_at: 2022-05-26 10:18:15.000, updated_at: 2022-05-26 10:18:15.000}}';
    String isJson = notJson.replaceAllMapped(RegExp(r'(?<=\{| )\w(.*?)(?=\: |, |})'), (match) {
      return '"${match.group(0)!}"';
    });
    print(isJson);
}

如果在更复杂的情况下进行解析,可能会受到修改。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章