Fetch a data from a string - javascript

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

Related

Unable to change/fetch the JSON value using REGEX and it returned Undefined

I'm trying to fetch the value of currency from the JSON file and if it's USD then I need to change it to AUD.
When I tried to search the currency attribute in the json file return undefined as below:
Code:
var datastring = JSON.stringify(data);
var match = /"currency":(^")*/.exec(datastring);
console.log(match ? "Got " + match[1] : "No match");
Output:
Got undefined
data.json:
{
"bank":[
{
"bankAccountType":"Saving",
"country":"US",
"currency":"USD",
"firstName":"TestFirstName",
"lastName":"TestLastName",
"confirmed":"true"
}
]
}
Can someone help me how to update the currency value in the JSON file and why it's returning 'undefined'
Thanks in advance.
Updated:
The data.json is dynamic json file and the structure will differ in every few minutes of interval. I'm only interested to get currency attribute which is always available from the data.json file and update the json before invoke it to server.
The regex is wrong. Try /"currency":"([^"]*)"/.
In general, doing a string match like this on structured data like JSON is likely to cause more problems than it solves: if the data is always similarly structured, you can manipulate it much more cleanly based on that structure; if it's not always similarly structured, you have no guarantee that the string manipulation is going to always do what you want.
Nonetheless, your regex is a simple one, but contains several mistakes:
/"currency":(^")*/
"currency": will match literally; so far, so good (as long as there's no extra whitespace in the JSON file)
(: start a capturing group
^: matches the start of the string; this can't possibly succeed here
": matches a literal "
)*: end the capturing group, and say that it can occur zero or more times
Instead of (^") you probably meant [^"] which means "any single character except for "". But that still won't work, because the character after the : is a ", so you need to match that first.
Instead of *, you probably want +, which means "one or more"; or just {3}, for "exactly three".
Finally, you want to capture the whole 3-character currency, not just the first part of it, so the brackets need to go around the whole thing.
Putting it together:
/"currency":"([^"]+)"/
Or:
/"currency":"([^"]{3})"/
Or, you could go much simpler, and use three "any single character" wildcards:
/"currency":"(...)"/
Here an example of how to do that.
let data = {
"bank":[
{
"bankAccountType":"Saving",
"country":"US",
"currency":"USD",
"firstName":"TestFirstName",
"lastName":"TestLastName",
"confirmed":"true"
}
]
};
var datastring = JSON.stringify(data);
console.log(datastring);
var match = /"currency":\"[A-Z]{3}\"/.exec(datastring)[0];
let currencyVal = match.split(":")[1].replaceAll('"', '');
console.log(currencyVal);
//Too can do directly from data
console.log(data.bank[0].currency);
//If the data is a string you can use JSON.parse() function for get a JSON object.
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
//Supposing you get the JSON with type string:
let jsonObj = JSON.parse(datastring);
console.log(jsonObj.bank[0].currency);
//If you want replace USD to AUD you can do for example:
jsonObj.bank[0].currency = jsonObj.bank[0].currency.replace("USD", "AUD");
console.log(jsonObj.bank[0].currency);
You can change from USD to AUD using the following regex;
/(?<="currency":")[^"]+/
const data = {
bank: [{
bankAccountType: "Saving",
country: "US",
currency: "USD",
firstName: "TestFirstName",
lastName: "TestLastName",
confirmed: "true",
}, ],
};
var datastring = JSON.stringify(data);
const replacedString = datastring.replace(/(?<="currency":")[^"]+/, "AUD");
console.log(replacedString);
const data = {
bank: [
{
bankAccountType: 'Saving',
country: 'US',
currency: 'USD',
firstName: 'TestFirstName',
lastName: 'TestLastName',
confirmed: 'true'
}
]
}
const datastring = JSON.stringify(data)
const replace = datastring.replace(/"currency":"([^"]*)"/, '"currency":"AUD"')
const reparsed = JSON.parse(replace)
console.log(reparsed)

How to remove special character from Json without parsing

I want to remove some special character from json without parsing
the json into object.
Parsing would result into error that is why i wanted to do without json.parse().
below is my json:
{
"id":324,
"name":"first",
"body":{
"sbody": "<p>\\\The New Stroy\\\</p>"
}
}
desired output:
{
"id":324,
"name":"first",
"body":{
"sbody": "<p> The New Stroy </p>"
}
}
Looks like your input is a string and the error you are getting is when using JSON.parse.
Try this
var response = '{"sbody": "<p>\\\The New Stroy\\\</p>"}';
response = response.replace(/\\/g, "");
var obj = JSON.parse(response);
console.log(obj);
You need to run .replace on your string:
var string = '{"id":324,"name":"first","body":{"sbody":"<p>\\\The New Stroy\\\</p>"}}';
string = string.replace(/\\/g,'');
console.log(string);
//{"id":324,"name":"first","body":{"sbody":"<p>The New Stroy</p>"}}
The reason the pattern is /\\/ is because \ is used to escape characters. With a single \ we end up escaping the /. What we need to do here is escape the escape character to turn it into a literal string character: \\.
The g after the pattern means to search for the pattern "globally" in the string, so we replace all instances of it.
var obj = {
"id":324,
"name":"first",
"body":{
"sbody": "<p>\\\The New Stroy\\\</p>"
}
}
// Convert object to string
var str = JSON.stringify(obj);
// Remove \ from the string
var convertedStr= str.replace(/\\/g,'');
// Convert updated string back to object
var newObj = JSON.parse(convertedStr);

Javascript Regular expression to wrap unquoted JSON Values (NOT keys) with double quotes

I have been trying to wrap some malformed JSON values with double quotes. The response is from a Java Servlet (its actually a hashmap) which I have no control over. I have managed to get it from this:
{ response={ type=000, products=[{id=1,name=productone},{id=2,name=producttwo}],status=success}}
to this:
{"response": { "type": 000, "products": [{"id": 1,"name": productone},{"id": 2,"name": producttwo}],"status": success}}
using the following regexes:
hashmap = hashmap
.replace (/ /g,"").replace(/\s/g,"") //replace all spaces
.replace (/'/g,"").replace(/"/g,'') //replace all quotes
.replace(/=/g,":") //replace = with :
.replace(/(['"])?([a-z0-9A-Z_]+)(['"])?:/g, '"$2": '); //put quotes around keys
How would I go around wrapping the values with double quotes using a regex. Any help is highly appreciated.
EDIT :
I would eventually want it to be in this form :
{"response": { "type": "000", "products": [{"id": "1","name": "productone"},{"id": "2","name": "producttwo"}],"status": "success"}}
Here's a way to quote all keys and values, as you want:
hashmap = hashmap.replace(/ /g, '') // strip all spaces
.replace(/([\w]+)=/g, '"$1"=') // quote keys
.replace(/=([\w]+)/g, ':"$1"') // quote values
.replace(/=([[{])/g, ':$1'); // = to : before arrays and objects also
This produces:
{"response":{"type":"000","products":[{"id":"1","name":"productone"},{"id":"2","name":"producttwo"}],"status":"success"}}
Now you can convert it to JavaScript object with:
obj = JSON.parse(hashmap);
However, more in line with JSON parsing would be not to quote numeric values, but rather to parse them as numbers, like this:
hashmap = hashmap.replace(/ /g, '')
.replace(/([\w]+)=/g, '"$1"=')
.replace(/=([a-zA-Z_]+)/g, ':"$1"')
.replace(/=([\d]+)/g, function(m, num) {return ':'+parseFloat(num)})
.replace(/=([[{])/g, ':$1')
This produces:
{"response":{"type":0,"products":[{"id":1,"name":"productone"},{"id":2,"name":"producttwo"}],"status":"success"}}

Slashes in json returned from node

I am getting slashes in the json returned from Node server. This is giving challenges in parsing the json.
The json looks like
"{\"responseCode\":200,\"headers\":{\"Access-Control-Allow-Origin\":\"*\",\"Content-Type\":\"application/json; charset=utf-8\",\"X-Powered-By\":\"Express\",\"Connection\":\"keep-alive\",\"Date\":\"Thu, 22 Sep 2016 08:12:39 GMT\",\"Content-Length\":\"21\",\"Etag\":\"W/\\"15-HeifZ4bmt+WxpIWDoartGQ\\"\"},\"response\":\"{\\"status\\":\\"UP\\"}\",\"bytesSent\":715779}"
In order to get rid of the slashes, I did a replace and then converted it back to json using JSON.parse
.then(function (result) {
var status = "";
var str = JSON.stringify(result);
console.log("str result ", str);
str = str.replace(/\\/g, "");
console.log("result after cleanup ", str);
var obj = JSON.parse(str);
status = obj.response.status;
}
After replacing the slashes, the string looks like this
"{\"responseCode\":200,\"headers\":{\"Access-Control-Allow-Origin\":\"*\",\"Content-Type\":\"application/json; charset=utf-8\",\"X-Powered-By\":\"Express\",\"Connection\":\"keep-alive\",\"Date\":\"Thu, 22 Sep 2016 08:12:39 GMT\",\"Content-Length\":\"21\",\"Etag\":\"W/\"15-HeifZ4bmt+WxpIWDoartGQ\"\"},\"response\":\"{\"status\":\"UPLOADED\"}\",\"bytesSent\":715779}"
When I try to parse it to JSON object, it throws an error on
var obj = JSON.parse(str);
It seems that the JSON is still invalid due to the slashes which still exist.
I have the following queries -
How can I update my regex to get rid of these slashes as well
Why do these slashes get introduced in the response
JSON.stringify() is the method used to generate a JSON string. If you apply it to something that's already a JSON string then you'll get a double-encoded JSON string:
var alreadyJson = '{"foo": "bar"}';
var doubleEncoded = JSON.stringify(alreadyJson);
console.log(doubleEncoded , typeof doubleEncoded);
"{\"foo\": \"bar\"}" string
What you need to use is the JSON.parse() method:
var alreadyJson = '{"foo": "bar"}';
var decoded = JSON.parse(alreadyJson);
console.log(decode, typeof decoded);
{ foo: 'bar' } 'object'
You don't need regx to eliminate slashes.
var response = '{\"responseCode\":200,\"headers\":{\"Access-Control-Allow-Origin\":\"*\",\"Content-Type\":\"application/json; charset=utf-8\",\"X-Powered-By\":\"Express\",\"Connection\":\"keep-alive\",\"Date\":\"Thu, 22 Sep 2016 08:12:39 GMT\",\"Content-Length\":\"21\",\"Etag\":\"W/\\"15-HeifZ4bmt+WxpIWDoartGQ\\"\"},\"response\":\"{\\"status\\":\\"UP\\"}\",\"bytesSent\":715779}';
JSON.parse(response);
This will give you JSON object eliminating slashes.
Reference
If I put some newlines in your string, it looks like this:
"{
\"responseCode\":200,
\"headers\":{
\"Access-Control-Allow-Origin\":\"*\",
\"Content-Type\":\"application/json; charset=utf-8\",
\"X-Powered-By\":\"Express\",
\"Connection\":\"keep-alive\",
\"Date\":\"Thu, 22 Sep 2016 08:12:39 GMT\",
\"Content-Length\":\"21\",
\"Etag\":\"W/\\"15-HeifZ4bmt+WxpIWDoartGQ\\"\"
},
\"response\":\"{\\"status\\":\\"UP\\"}\",
\"bytesSent\":715779
}"
We can see that one of the issue is at line Etag. The part \\"15 should be \\\"15. One backslash to espace the next backslash, then again a backslash to espace the quote.
It's the same issue for status and UP. Fix your server :)

Parse string having key=value pairs as JSON

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(" ", "&")));

Categories

Resources