admin管理员组文章数量:1187674
My node app receives a series of strings in the format "a=x b=y c=z"
(i.e. a string containing several space-separated key=value
pairs).
What is the neatest way of converting such a string into a JSON object of the form {a: x, b: y, c: z}
?
I'm betting that there's a one-line solution, but haven't managed to find it yet.
Thanks.
My node app receives a series of strings in the format "a=x b=y c=z"
(i.e. a string containing several space-separated key=value
pairs).
What is the neatest way of converting such a string into a JSON object of the form {a: x, b: y, c: z}
?
I'm betting that there's a one-line solution, but haven't managed to find it yet.
Thanks.
Share Improve this question asked Aug 20, 2015 at 19:39 drmrbrewerdrmrbrewer 13k23 gold badges97 silver badges211 bronze badges 2- What kind of data is in the values? Strings? Numbers? – Andreas Hagen Commented Aug 20, 2015 at 19:44
- 1 You say that you want a "JSON object" as result, but there is no such thing. JSON is a text format for representing data. Do you want the result to be JSON or an object? – Guffa Commented Aug 20, 2015 at 19:49
8 Answers
Reset to default 10One way would be to replace the with a
,
and an =
with a :
:
var jsonStr = '{' + str.replace(/ /g, ', ').replace(/=/g, ': ') + '}';
Or if you need quotes around the keys and values:
var jsonStr2 = '{"' + str.replace(/ /g, '", "').replace(/=/g, '": "') + '"}';
JSON.parse()
it if you need.
Sample output:
str: a=x b=y c=z
jsonStr: {a: x, b: y, c: z}
jsonStr2: {"a": "x", "b": "y", "c": "z"}
Building on John Bupit's excellent answer, I have made a couple of further enhancements to end up with the following (the string being parsed being in message
):
var json = JSON.parse(('{"' + message.replace(/^\s+|\s+$/g,'').replace(/=(?=\s|$)/g, '="" ').replace(/\s+(?=([^"]*"[^"]*")*[^"]*$)/g, '", "').replace(/=/g, '": "') + '"}').replace(/""/g, '"'));
Basically the scheme is as follows:
- First
replace()
: trim off any leading or trailing whitespace -- equivalent totrim()
- Second
replace()
: add double quotes (empty string) for any value that is completely missing (e.g.key1= key2=val
goes tokey1="" key2=val
). - Third
replace()
: replace each space (which acts as a delimiter) with", "
, but not where the space is within double quotes (i.e. part of a string value). - Fourth
replace()
: replace each=
with": "
- Wrap the entire string up as follows:
{"..."}
- Finally, replace any double quotes
""
created by the above steps (because the value string was already wrapped in quotes inmessage
) with single quotes"
- Even more finally, run
JSON.parse()
over the result.
The above scheme should cope with missing values, with some values being quoted and some unquoted, and with spaces within value strings, e.g. something like a= b="x" c="y y" d=z
.
Assuming that you don't get nested objects in that format :
var sample = 'a=x b=y c=z';
var newobj = {};
sample.split(' ').forEach(function (value) {
var keypair = value.split('=');
newobj[keypair[0]] = keypair[1];
});
console.dir(newobj);
What this does is split on every white-space and push to an array, and the array is looped and each item in array is split again to get each key-value pair which is assigned to the newobj.
Here's a simple function that will do the trick
function stringToObj (string) {
var obj = {};
var stringArray = string.split(' ');
for(var i = 0; i < stringArray.length; i++){
var kvp = stringArray[i].split('=');
if(kvp[1]){
obj[kvp[0]] = kvp[1]
}
}
return obj;
}
I would use an approach leveraging URLSearchParams
and Object.fromEntries()
like so:
const input = "a=x b=y c=z";
const queryString = input.replaceAll(" ", "&");
const query = new URLSearchParams(queryString);
const output = Object.fromEntries(query);
console.log(output);
Breakdown:
The URLSearchParams
constructor takes a string of key-value pairs joined by "&" as it's argument, and parses it into a URLSearchParams
object instance. So to use this, the space separators in the original input need to be replaced with a "&" character.
The URLSearchParams
instance we have after parsing is an iterable, so we can transform it into a plain Object with Object.fromEntries()
.
It's not too bad as a one-liner either:
const input = "a=x b=y c=z";
const output = Object.fromEntries(new URLSearchParams(input.replaceAll(" ", "&")));
newstr = ""
for kvp in @value.split(" ")
newstr += kvp.replace(/=/,'":"').replace(/^/, '"').replace(/$/, '"').replace(/\"\"/,'" "')
newstr = newstr.replace(/\"\"/g, '","')
jsn = JSON.parse('{' + newstr + '}')
I created a simple online tool for similar need: https://superal.github.io/online-tools/
Use cases:
To transfer key:value pairs copied from chrome network requests(form data or query string parameters) or postman headers key-value(in bulk edit style) to json format.
For example:
key:value pairs
platform:2
limit:10
start_time:1521561600
end_time:1522080000
offset:0
to json format
{
"platform": "2",
"limit": "10",
"start_time": "1521561600",
"end_time": "1522080000",
"offset": "0"
}
It can be parsed (converted to json) using the help of this npm athena-struct-parser package.
For more information about the package -- https://www.npmjs.com/package/athena-struct-parser
Sample Nodejs Code
var parseStruct =require('athena-struct-parser') ;
var str = '{description=Check the Primary key count of TXN_EVENT table in Oracle, datastore_order=1, zone=yellow, aggregation_type=count, updatedcount=0, updatedat=[2021-06-09T02:03:20.243Z]}'
var parseObj = parseStruct(str)
console.log(parseObj);
Sample string with key=value format taken
{description=Check the Primary key count of TXN_EVENT table in Oracle, datastore_order=1, zone=yellow, aggregation_type=count, updatedcount=0, updatedat=[2021-06-09T02:03:20.243Z]}
Result Parsed output
{
description: 'Check the Primary key count of TXN_EVENT table in Oracle',
datastore_order: '1',
zone: 'yellow',
aggregation_type: 'count',
updatedcount: '0',
updatedat: [ '2021-06-09T02:03:20.004Z' ]
}
本文标签: javascriptParse string having keyvalue pairs as JSONStack Overflow
版权声明:本文标题:javascript - Parse string having key=value pairs as JSON - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738352318a2079205.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论