I have a String in Javascript. It looks somewhat like this:
' "foo": "" , /n "bar": "" '
I need it so I can do a request for a API, and the request is made like this:
$http
.post(urlToAPI, {
"foo": "",
"bar": ""
})
.success(function(data) {
console.log("yay")
})
As you can see, as a parameter, I'm giving the post method a structure that contains both foo and bar. The problem is that I can't pass my own string in there, because I need to Parse it before.
So, basically, I need this
' "foo": "" , /n "bar": "" '
To become this:
"foo": "", "bar": ""
I tried to use JSON.parse(), but it won't work, since it's not a JSON object.
I also tried some CSV converters, but it seems like that isn't a CSV either. I don't even know the name of that kind of structure, so I've been struggling a bit on how to parse it.
Do you have any clue?
Assuming you really mean /n and not \n
var str = ' "foo": "" , /n "bar": "" ';
JSON.parse(('{' + str + '}').replace(' /n', ''));
With a bit of massaging you can format the string properly and put its values into an object. Then just pass the whole object into your AJAX call:
.post(urlToAPI, obj)
let str = ' "foo": "" , /n "bar": "" ';
const arr = str.trim().replace("/n","").split("\"").join("").split(",");
const obj = {};
arr.forEach((el, idx) => {
let arr2 = el.split(":");
obj[arr2[0].trim()] = arr2[1].trim();
});
console.log(obj);
I assume the /n is actually a \n (newline). If that is the case, you can parse your string as json taking advantage of the eval function:
var input=' "foo": "" , \n "bar": "" ';
var serial="json={"+input+"}";
var json=eval(serial);
// Now you can access json.foo and json.bar
Related
I am trying to stringify the object which has another stringify object. I am getting \added to inside object
a = {}
str = {'a': 'test'}
a.str = JSON.stringify(str);
console.log("=="+ (a));
console.log("strin " + JSON.stringify(a) ) // {"str":"{\"a\":\"test\"}"}
expected: {"str":"{"a":"test"}"}
What you expect would not be valid JSON.
Quotes are used to delimit strings in a JSON text.
With your expected result a JSON parser would see "{" and think that was the whole string and then a would be an error.
The escape sequence \" is how you say "This is a quote that is a part of a string" instead of "This is a quote that ends the string".
The output is fine. There is nothing wrong.
That said, nesting JSON is generally a bad idea. It is more complicated to parse and harder to read.
In general you should be creating the complete data structure and then stringifying that.
const a = {};
const str = {
'a': 'test'
};
a.str = str;
const json = JSON.stringify(a, null, 2);
console.log(`result: ${json}`);
There is an error
str = {'a': 'test}
It should be
str = {'a': 'test'}
The reason you are getting '' is simply because they are escaping double strings
This is illegal:
"{"str":"{"a":"test"}"}"
This is legal:
"{\"str\":\"{\"a\":\"test\"}\"}"
I have below json data I need to replace "=" to ":" by Javascript
{ "name"="John", "age"=30, "car"=null }
Expected output:
{ "name":"John", "age":30, "car":null }
This should do the trick:
var str = '{ "name"="John", "age"=30, "car"=null }';
str = str.replace(/=/g,":");
var json = JSON.parse(str);
Note, that it would convert ALL "=" to ":". If there can be symbol in name or value, different approach should be used.
--
Update "g" modifier has to be used if there is more than one "=" to replace.
Use g flag:
'{ "name"="John", "age"=30, "car"=null }'.replace(/\=/g, ':')
You can use Replace
let op = `{ "name"="John", "age"=30, "car"=null }`.replace(/=/g, ':')
console.log(op)
I have a big array of objects that contains a string property. When I save my object called data to a file in json, the string property came with breaks words like "getElementsByTagName(\"track\")". I need to get like that: "getElementsByTagName("track")" without \.
my code:
var jsonobj = JSON.stringify(data,null,'\t');
fs.write('final8.json', jsonobj, 'w');
You can avoid escaping by using single quotes. For example you can replace " with ' using custom serializer.
var data = {test: 'getElementByTagName("track")'}
JSON.stringify(data, function(key,value) {
if(typeof value === 'string') {
return value.replace(/"/g, '\'')
}
return value
}, '\t');
"{
"test": "getElementByTagName('track')"
}"
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.
One 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 to trim()
Second replace(): add double quotes (empty string) for any value that is completely missing (e.g. key1= key2=val goes to key1="" 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 in message) 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;
}
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' ]
}
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(" ", "&")));
I have this as a string. I have get this using jquery and parsing it from a web page.
I tried using jQuery.parseJSON and got the error Uncaught SyntaxError: Unexpected token n.
I need to get "surl" and "imgurl" how can I get this?
{
ns:"images",
k:"5061",
mid:"172E23D582B8C2A90F3FE9DC2B04A3ECD1D4F70F",
surl:"http://polyhouse2011.wordpress.com/2011/05/16/safety-precautions-2/",
imgurl:"http://polyhouse2011.files.wordpress.com/2011/05/safety_gear1.gif",
ow:"480",
docid:"608038082569896450",
oh:"301",
tft:"117",
dls:"images,5487"
}
Source of this string:
My example assumes your anchor has an id for convenience. If you use wrxsti's answer without all the unnecessary escaping, you get this:
var str = document.getElementById('a').getAttribute('q');
var json = JSON.stringify(eval("(" + str + ")"));
var obj = JSON.parse(json)
var surl = obj.srl;
DEMO
But you really should get that attribute data changed to proper parsing JSON.
If you do not have the option of editing the JSON information you can do this to make it a valid json object. I will say that including eval can be bad due to security reasons, but this will make your JSON a valid object in the long run.
var object = '{ \
ns: "images", \
k: "5061", \
mid: "172E23D582B8C2A90F3FE9DC2B04A3ECD1D4F70F", \
surl: "http://polyhouse2011.wordpress.com/2011/05/16/safety-precautions-2/", \
imgurl: "http://polyhouse2011.files.wordpress.com/2011/05/safety_gear1.gif", \
ow: "480", \
docid: "60808082569896450", \
oh: "301", \
tft: "117", \
dls: "images5487" \
}';
var json = JSON.stringify(eval("(" + object + ")"));
var o = $.parseJSON(json);
DEMO
Hope this helps. Let me know if you have any questions!
this is a valid your JSON string :
{
"ns": "images",
"k": "5061",
"mid": "172E23D582B8C2A90F3FE9DC2B04A3ECD1D4F70F",
"surl": "http://polyhouse2011.wordpress.com/2011/05/16/safety-precautions-2/",
"imgurl": "http://polyhouse2011.files.wordpress.com/2011/05/safety_gear1.gif",
"ow": "480",
"docid": "608038082569896450",
"oh": "301",
"tft": "117",
"dls": "images,5487"
}
if you get some error in your JSON string then check its validation online through http://jsonlint.com/ i hope it will help you.
You use object format not json format, it is correct if you do like the following code:
var obj = {
ns:"images",
k:"5061",
mid:"172E23D582B8C2A90F3FE9DC2B04A3ECD1D4F70F",
surl:"http://polyhouse2011.wordpress.com/2011/05/16/safety-precautions-2/",
imgurl:"http://polyhouse2011.files.wordpress.com/2011/05/safety_gear1.gif",
ow:"480",
docid:"608038082569896450",
oh:"301",
tft:"117",
dls:"images,5487"
}
Therefore, if you want to get surl and imgurl: just do: obj.surl; and obj.imgurl