"-6ren">
gpt4 book ai didi

javascript - 如何将带有序列化的 PHP 代码转换为 javascript 代码?

转载 作者:行者123 更新时间:2023-11-30 13:55:25 26 4
gpt4 key购买 nike

我得到了这行 PHP 代码,但我不知道如何用 Javascript 准确翻译它。

PHP代码:

$data = ['username' => "myUsername", 'password' => "myPassword"];
serialize($data);

这是准确翻译的 javascript 代码吗?JS代码:

let data = [{'username': "myUsername"}, {'password': "myPassword"}];
JSON.stringify(data);

原始代码是用 PHP 编写的。所以我需要修改node.js中的javascript

最佳答案

差不多就好了

要将 php 数组转换为 js,您有两种解决方案:

如果它是一个 key => value 数组,它会转换为一个对象

$data = ['username' => "myUsername", 'password' => "myPassword"];

成为

let data = {'username': "myUsername", 'password': "myPassword"};

; 是可选的并且引号 ",' 在 php AFAIK 中工作

while PHP arrays without key translate to js array

$data = ["myUsername", "myPassword"];

成为

let data = ["myUsername", "myPassword"]

这些都是相似的


了解如何转换结构的一种方法是在 php 中对它们进行 json_encode,因为 JSONjs< 的子集(不完美,但这些都是边缘情况 AFAIK),您可以使用给定的 JSON 作为 js

中的变量声明

// PHP :
// json_encode(['username' => "myUsername", 'password' => "myPassword"]);
// returns {"username":"myUsername","password":"myPassword"}

let myObject = {"username":"myUsername","password":"myPassword"}
console.log(myObject)

// same with non keyed array
// json_encode(["myUsername", "myPassword"]);
// returns ["myUsername","myPassword"]
let myArray = ["myUsername","myPassword"]
console.log(myArray)


这里是尝试创建serialize在 javascript 中

Makopa给了this node package which do the serialization如果可以,请在评论中使用它,因为它比我制作的这个小脚本效果更好

警告它不会像序列化一样工作,因为:

  • 我找不到如何序列化回调函数,因为我无法让它工作,所以如果有人有可用的示例,我很乐意添加它

  • JavaScript 对对象中的私有(private)/ protected 属性一无所知

  • JavaScript 不会区分 int 和 double/float

  • 我可能忘记测试而没有实现的任何其他情况

  • 如果你们发现任何错误,请不要犹豫,在评论中告诉我

let serialize = value => {
let serializeNull = value => {
return `N;`
}
let serializeBool = value => {
return `b:${value?1:0};`
}
let serializeInt = value => {
return `i:${parseInt(value)};`
}
let serializeDouble = value => {
return `d:${value};`
}
let serializeString = value => {
return `s:${value.length}:"${value}";`
}
let serializeArray = value => {
let serialized = `a:${value.length}:{`
value.forEach((val, i) => {
serialized += serialize(i)
if(val === value) {
throw new Error("sorry doesn't support array referencing themselves")
} else {
serialized += serialize(val)
}

})
return serialized + "}"
}
let serializeKeyedArray = value => {
let entries = Object.entries(value)
let serialized = `a:${entries.length}:{`
entries.forEach(entry => {

serialized += serialize(entry[0])
if(entry[1] === value) {
throw new Error("sorry doesn't support array referencing themselves")
} else {
serialized += serialize(entry[1])
}

})
return serialized + "}"
}
let serializeObject = value => {
let entries = Object.entries(value)
let serialized = `O:${value.constructor.name.length}:"${value.constructor.name}":${entries.length}:{`
entries.forEach(([key, val]) => {

serialized += serialize(key)
// if protected key should become \0*\0${key}
// if private key should become \0${value.constructor.name}\0${key}

if(val === value) {
serialized += "r:1;"
} else {
serialized += serialize(val)
}

})
return serialized + "}"
}

switch(typeof value) {
case "number": // int or double
if (""+value == parseInt(""+value)) { return serializeInt(value) }
else { return serializeDouble(value) }
break
case "boolean": // boolean
return serializeBool(value)
break
case "string": // string
return serializeString(value)
break
case "undefined": // undefined
return serializeNull(value)
break
case "object": // Array, primitive object, object from class or null
if (Array.isArray(value)) { return serializeArray(value) }
else if (value === null) { return serializeNull(value) }
else if (value.constructor.name !== "Object") { return serializeObject(value) }
else { return serializeKeyedArray(value) }
break
default: throw new Error("sorry I don't know how to serialize this")
}
}

class TestClass {
constructor() {
this.self = this
this.a = 42
this.b = "How are you ?"
}
}

let tests = [
{expected: `i:1;`, val: 1},
{expected: `i:-1;`, val: -1},

{expected: `d:1;`, val: 1.0},
{expected: `d:1.5;`, val: 1.5},
{expected: `d:-4.2;`, val: -4.2},

{expected: `b:1;`, val: true},
{expected: `b:0;`, val: false},

{expected: `N;`, val: null},
{expected: `N;`, val: undefined},

{expected: `s:4:"test";`, val: "test"},
{expected: `s:5:"hello";`, val: "hello"},

{expected: `a:3:{i:0;i:1;i:1;s:2:"hi";i:2;i:5;}`, val: [1, "hi", 5]},

{expected: `a:3:{s:1:"a";i:1;s:1:"b";s:2:"hi";s:1:"c";i:5;}`, val: {a:1, b:"hi", c:5}},

{expected: `O:9:"TestClass":3:{s:4:"self";r:1;s:1:"a";i:42;s:1:"b";s:13:"How are you ?";}`, val: new TestClass()}
]

tests.forEach(val => {
let serialized = serialize(val.val)
let log = `expected : '${val.expected}', got : '${serialized}', value : ${(()=>{
if(typeof val.val === "object") {
return val.val ? Object.entries(val.val).join(", ") : val.val // null
} else {
return val.val ? val.val.toString() : val.val // undefined
}
})()}`
if(val.expected === serialized) {
console.log(log)
} else {
console.error(log)
}
})

如您所见,仍有错误:

  • double 在点后没有有用的数字(比如 1.0000)被认为是 int 因为在 JS 中它们是相同的 号码

返回值基于 serializethis site 上的返回值2019 年 8 月 7 日和 8 日运行 php 7.3.5

关于javascript - 如何将带有序列化的 PHP 代码转换为 javascript 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57396757/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com