问题
I'm trying to write a function that takes some object, for example a number, a string, a list, or a map (of key-value pairs); and returns a valid JSON representation of that input as a string.
I have already set up other json encoders for simple numbers and string inputs:
Input => Output
a number with value 123 => 123 (string)
a string with value abc => "abc" (string)
But I'm having issues converting an array such as [1,"2",3]
Input => Output
1,2,three array => [1,2,"three"] (string)
Here is my current code:
var my_json_encode = function(input) {
if(typeof(input) === "string"){
return '"'+input+'"'
}
if(typeof(input) === "number"){
return `${input}`
}
//This is causing my issue
if(Array.isArray(input)) {
console.log(input)
}
I could simply add and return JSON.stringify(input) to change it but I don't want to use that. I know I can create some sort recursive solution as I have base cases set up for numbers and strings. I'm blocked on this and any help will be appreciated
Edit: So the solution as been provided below in the answers section! Thanks :)
回答1:
For arrays take a recursive approach with the items.
const
json_encode = (input) => {
if (typeof input === "string") return `"${input}"`;
if (typeof input === "number") return `${input}`;
if (Array.isArray(input)) return `[${input.map(json_encode)}]`;
};
console.log(json_encode([1, 'foo', [2, 3]]));
console.log(JSON.parse(json_encode([1, 'foo', [2, 3]])));
回答2:
You already have the function that converts scalar values to json values.
So, you can call this function for all array's member (e.g. using https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/map) and then join it (https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/join) and add '[' and ']' to the resulting string
PS: this approach will work also in situations when you have an array of arrays
Example of the implementation:
var my_json_encode = function(input) {
if(typeof(input) === "string"){
return '"'+input+'"'
}
if(typeof(input) === "number"){
return `${input}`
}
if(Array.isArray(input)) {
const formatedArrayMembers = input.map(value => my_json_encode(value)).join(',');
return `[${formatedArrayMembers}]`;
}
}
来源:https://stackoverflow.com/questions/61467079/converting-array-to-valid-json-string-without-using-json-stringify