javascript json uncaught syntaxerror unexpected token illegal - javascript

I am getting server response json with special character, How can i remove this special charecter from it. It tried replace() but its not working. My json sample is here
{
"#tag":"1013170",
"#title":"Holman Rd & Trestle Glen Rd",
"#lat":"37.8067794",
"#lon":"-122.2325773",
"#stopId":"52750"
}

try something like this
var str = '{"#tag":"1013170","#title":"Holman Rd & Trestle Glen Rd","#lat":"37.8067794","#lon":"-122.2325773","#stopId":"52750"}';
console.log(str.replace(/#/g,''));
//will give you
{"tag":"1013170","title":"Holman Rd & Trestle Glen Rd","lat":"37.8067794","lon":"-122.2325773","stopId":"52750"}
By the way your json is valid
var json ={"#tag":"1013170","#title":"Holman Rd & Trestle Glen Rd"};
//var json_obj = $.parseJSON(json);//don't do this because it already json.
console.log(json.#tag); // don't use this way
console.log(json['#tag']);// instead try this way

You can't change a property name, you have to add the value with a new name and delete the old property:
object = {
"#tag":"1013170",
"#title":"Holman Rd & Trestle Glen Rd",
"#lat":"37.8067794",
"#lon":"-122.2325773",
"#stopId":"52750"
}
for (var property in object) {
if (object.hasOwnProperty(property)) {
object[property.slice(1)]=object[property];
delete object[property];
}
}
console.log(object) will now give you
{tag: "1013170", title: "Holman Rd & Trestle Glen Rd", lat: "37.8067794", lon: "-122.2325773", stopId: "52750"}

Finally i read the json with this line.
result['#tag']
Its simple you can read json from '.' notation and from [], the second one reads special character as well.

Related

I get an object as a string. How to convert?

Using IMAP I receive an email.
But parsing, I get this:
{
from: [ "name lastname <mygmail#gmail.com>" ],
date: [ "Mon, 21 Jun 2021 13:41:51 +0500" ],
subject: [ "hello" ]
}
The catch is that this is a string, not an object at all!
I cannot take advantage of this.
How do I convert this string to an object?
JSON.parse() throws an error message:
UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token f in JSON at position 141
You get that error because in JSON notation properties should be enclosed in double quotes like this:
{
"from": [ "name lastname <mygmail#gmail.com>" ],
"date": [ "Mon, 21 Jun 2021 13:41:51 +0500" ],
"subject": [ "hello" ]
}
So, if what you get is a string like what you showed, you'll have to add these double quotes yourself (maybe with a nice and coolio regex)
As others have noted, because this is not JSON, you can't parse it as JSON. What it does appear to be is a JavaScript snippet.
In the past eval(customJavaScriptCode) would have been used for this but it is very insecure so avoid it.
A better and safer (but not bulletproof) way is to run the JavaScript in a sandbox environment. It's hard to break out of that. You do that like this:
Prefix your object with result = , the name doesn't really matter.
Execute the JavaScript in a sandbox.
Get the value of the last statement.
const vm = require('vm');
const script = new vm.Script('result = ' + `{
from: [ "name lastname <mygmail#gmail.com>" ],
date: [ "Mon, 21 Jun 2021 13:41:51 +0500" ],
subject: [ "hello" ]
}`);
const lastStatementResult = script.runInNewContext();
console.log(lastStatementResult.subject[0] == "hello");
You now have the object parsed as JS in a relatively safe way.
If you need more than just the last statement, you can do this like this:
const vm = require('vm');
const script = new vm.Script(`
var foo = "bar";
var baz = foo + "123";
`);
const context = {}; // will contain global variables from the script
script.runInNewContext(context);
console.log(context.foo + '123' === context.baz);
I was also running into this issue following the documentation to the letter. The problem is exactly how OP describes, there is a return value from one of Imap's callback functions that is shaped like an object, but does not respond to dot notation, nor JSON.parse/stringify.
The problem was using the suggested inspect property from the util node package. This is what is returning a string shaped like an object that is unusable. Instead, omit the inspect on the values you need to parse.
Original usage (straight from the docs) (bad)
stream.once('end', function() {
console.log(prefix + 'Parsed header: %s', inspect(Imap.parseHeader(buffer)));
});
My solution (good)
stream.once('end', function() {
console.log(prefix + 'Parsed header: %s', Imap.parseHeader(buffer));
});
All I did was omit the inspect. I can now assign Imap.parseHeader(buffer) to a variable and manipulate it just like a normal JS object.
I did not understand your question correctly.
Try this
JSON.stringify(JSON.parse(Object))
If error exist, Please describe your issue with more

Extract information from string - JavaScript

I am currently implementing google places autocomplete and the module I am using in React Native gives me the address as a whole string and not in address components. However, I need to have the postal code and city separate. The example response always look like this:
address: 'Calle Gran Vía, 8, 28013 Madrid, Spain
From this string I would need to have an object that looks like this:
{
city: 'Madrid',
postal_code: 28013,
}
How could I achieve this?
It's not the most "clean" or "smooth" answer, but it's something:
var response = "address: 'Calle Gran Vía, 8, 28013 Madrid, Spain";
var subStr = response.split(",")[2];
var obj = {
city: subStr.split(" ")[2],
postal_code: subStr.split(" ")[1]
};
console.log(obj);
For the city I think the best way is to use an array of cities and search it in the string
var str = "Calle Gran Vía, 8, 28013 Madrid, Spain";
var cities = ["Paris", "Berlin", "Madrid"];
var city = cities.filter(function(item) {
if (str.search(item) != -1)
return item;
})[0] || null;
For the postal code you should use a regex depending on the country (a good list of regex by country)
Probably split the string by ',' with array methods, take the third element of the array and split that by ' ', then you have your data points.
If you can always count on it being in that same format, you can do the following.
var splitAdress = address.split(",");
//This will give you ["Calle Gran Vía", " 8", " 28013 Madrid", " Spain"]
splitAdress = splitAdress[2].split(" ");
//This will give you ["", "28013", "Madrid"]
You'll first split the string into an array based on the comma and then follow it up by splitting on the space. The extra element in the second array is due to the space. This is an example of what #CBroe pointed out in the comments.
list=adress.split(",")[2].split()
list[0] gives you the postal code
list[1] gives you the city name
It depend on if there is always a comma in the "Calle Gran Vía, 8", if not you can use instead list=adress.split(",")[-2].split()
You might want to try this.
var address="Calle Gran Vía, 8, 28013 Madrid, Spain";
var splits = address.split(',')[2].trim().split(' ');
var newAdd = {
city : splits[1],
postal_code : splits[0]
}
console.log(newAdd);

How to extract information from a file with key value pair

I have a large number of txt file which contains information in a key value pair format
"Site Code": "LEYB"
"Also known as": ""
"Location": "Pier Site, Poblacion del Sur, Villaba, Southern Leyte"
"Contact person(s)": ""
"Coordinates[1]": "11 12 40.302622, 124 23 21.450632"
"Coordinates[2]": "11.211195, 124.389292"
"School ID": ""
"Site Description": "Benchmark LEYB is on end part of right side wall,leading to the seaport"
"Sketch": "./LEYB.docx"
"Constructed": "PHIVOLCS - October 2009"
"Method" : "Campaign"
All I want to do is to extract those information to create a master file. maybe in a column format such as csv, JSON or excel.
Can you suggest a tool or a file system strategy in Node.js that can achieve my goal.
Try this. Assuming file.txt is the file where you have the data in key value pair (but not in proper json format)
var fs = require("fs");
var content = fs.readFileSync("file.txt");
var lines = content.toString().split('\n');
var myObj = {};
for(var line = 0; line < lines.length; line++){
var currentline = lines[line].split(':');
myObj[currentline[0].trim().replace(/["]/g, "")] = currentline[1].trim().replace(/["]/g, "");
}
console.log(myObj);
This will give you a proper object which you can then use to convert to csv,json or whatever.
To convert to JSON use.
JSON.stringify(myObj);

Regular Expression: pull part from string. with JS

Hey all im not every good with regexp i was hoping someone could help.
ok so this is the sting "KEY FOUND! [ 57:09:91:40:32:11:00:77:16:80:34:40:91 ]"
And i need to pull "57:09:91:40:32:11:00:77:16:80:34:40:91", now this key can be meany length not just as written here and with or with out the ":"
now the second sting i would like to test and extract is: "[00:00:09] Tested 853 keys (got 179387 IVs)", i would like to pull "00:00:09" and "853" and "179387".
this would be the raw string http://regexr.com?31pcu or http://pastebin.com/eRbnwqn7
this is what im doing now.
var pass = new RegExp('KEY FOUND\!')
var tested = new RegExp('Tested')
var fail = new RegExp('\Failed. Next try with ([0-9]+) IVs')
var data="Look at the link i added"
if (tested.test(data)) {
self.emit('update', mac, {
'keys' : data.split('Tested ')[1].split(' keys ')[0],
'ivs' : data.split('got ')[1].split(' IVs')[0]
});
} else if (pass.test(data)) {
var key = data.split('KEY FOUND! [')[1].split(' ]')[0].split(':').join('');
} else if (fail.test(data)) {
console.log(data);
}
thanks all
Edit:
I have added more the the question to help with the answer
If it is always surrounded by [] then it is simple:
\[([\s\S]*)\]
This will match any characters enclosed by [].
See it in action here.

Parsing JSON with JSON.NET

I have a JSON string:
{"responseData":
{"results": [
{"GsearchResultClass": "GblogSearch",
"title":"\u003cb\u003eParis Hilton\u003c/b\u003e shops at Sydney Michelle boutique in the Beverly Glen \u003cb\u003e...\u003c/b\u003e",
"titleNoFormatting":"Paris Hilton shops at Sydney Michelle boutique in the Beverly Glen ...",
"postUrl":"http://www.celebrity-gossip.net/celebrities/hollywood/paris-hilton-sydney-michelle-stockup-215844/",
"content":"\u003cb\u003eParis Hilton\u003c/b\u003e shops at Sydney Michelle boutique in the Beverly Glen Mall - \u003cb\u003eParis Hilton\u003c/b\u003e: Sydney Michelle Stockup.",
"author":"The Gossip Girls at (c) gossipgirls.com",
"blogUrl":"http://www.celebrity-gossip.net/",
"publishedDate":"Tue, 23 Feb 2010 22:26:00 -0800"
},
{"GsearchResultClass":"GblogSearch",
"title":"\u003cb\u003eParis Hilton\u003c/b\u003e having wardrobe woes as she met with her lawyer",
"titleNoFormatting":"Paris Hilton having wardrobe woes as she met with her lawyer",
"postUrl":"http://www.celebrity-gossip.net/celebrities/hollywood/paris-hiltons-wardrobe-woes-215855/",
"content":"\u003cb\u003eParis Hilton\u003c/b\u003e having wardrobe woes as she met with her lawyer - \u003cb\u003eParis Hilton's\u003c/b\u003e Wardrobe Woes.",
"author":"The Gossip Girls at (c) gossipgirls.com","blogUrl":"http://www.celebrity-gossip.net/",
"publishedDate":"Wed, 24 Feb 2010 11:07:56 -0800"
},
{"GsearchResultClass":"GblogSearch",
"title":"HOT GALLERY: \u003cb\u003eParis Hilton\u003c/b\u003e Turns Her Frown Upside Down | OK \u003cb\u003e...\u003c/b\u003e",
"titleNoFormatting":"HOT GALLERY: Paris Hilton Turns Her Frown Upside Down | OK ...",
"postUrl":"http://www.okmagazine.com/2010/02/hot-gallery-paris-hilton-turns-her-frown-upside-down/",
"content":"\u003cb\u003eParis Hilton\u003c/b\u003e kept her game face on yesterday as she headed to a meeting in Hollywood. The socialite maintained her composure, but eventually cracked a smile, 201002.",
"author":"Brittany Talarico",
"blogUrl":"http://www.okmagazine.com/",
"publishedDate":"Wed, 24 Feb 2010 07:57:10 -0800"
},
{"GsearchResultClass":"GblogSearch",
"title":"Love It Or Hate It: \u003cb\u003eParis Hilton\u003c/b\u003e | ImNotObsessed.com",
"titleNoFormatting":"Love It Or Hate It: Paris Hilton | ImNotObsessed.com",
"postUrl":"http://www.imnotobsessed.com/2010/02/24/love-it-or-hate-it-paris-hilton",
"content":"tweetmeme_url \u003d \"http://www.imnotobsessed.com/2010/02/24/love-it-or-hate-it-\u003cb\u003eparis\u003c/b\u003e-\u003cb\u003ehilton\u003c/b\u003e\";tweetmeme_element_id \u003d '#tweetmeme-widget-139430e62dc37d7a2aa71840d6444572';That's some dress \u003cb\u003eParis Hilton\u003c/b\u003e was seen wearing while shopping in ...",
"author":"Vera",
"blogUrl":"http://www.imnotobsessed.com/",
"publishedDate":"Wed, 24 Feb 2010 10:44:28 -0800"
}],
"cursor": {
"pages": [
{"start":"0","label":1},
{"start":"4","label":2},
{"start":"8","label":3},
{"start":"12","label":4},
{"start":"16","label":5},
{"start":"20","label":6},
{"start":"24","label":7},
{"start":"28","label":8}],
"estimatedResultCount":"8035445",
"currentPageIndex":0,
"moreResultsUrl":"http://blogsearch.google.com/blogsearch?oe\u003dutf8\u0026ie\u003dutf8\u0026safe\u003dactive\u0026source\u003duds\u0026start\u003d0\u0026hl\u003den\u0026q\u003dParis+Hilton"
}
},
"responseDetails": null,
"responseStatus": 200}
ed. note: line breaks added for readability
and I'm using Json.NET to parse it, however its giving me a null
this is my code:
JObject o = JObject.Parse(json); // <- where json is the string above
string name = (string)o["responseData"];
BUT its giving me this error :
Can not convert {null} to String.
Using Json.Net, you can deserialize the object like this:
BlogSearch search = JsonConvert.DeserializeObject<BlogSearch>(content);
You would define the BlogSearch object like this:
[JsonObject(MemberSerialization.OptIn)]
public class BlogSearch
{
[JsonProperty(PropertyName = "responseData")]
public BlogSearchResponse SearchResponse { get; set; }
}
You keep defining objects until you have all the ones you are interested in.
Have you tried things like?
string gsearchresultclass= (string)o["responseData"]["results"][0]["GsearchResultClass"];
string title= (string)o["responseData"]["results"][0]["title"];
string titlenoformat= (string)o["responseData"]["results"][0]["titleNoFormatting"];
string url = (string)o["responseData"]["results"][0]["postUrl"];
string content = (string)o["responseData"]["results"][0]["content"];
string author = (string)o["responseData"]["results"][0]["author"];
string blogurl = (string)o["responseData"]["results"][0]["blogUrl"];
string date = (string)o["responseData"]["results"][0]["publishedDate"];
What exactly are you trying to get into the name variable?
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx
Its a good alternative to your method, that I would recommend...
Hope that helps...
If you're posting your JSON object raw to the Web API then you will run into this problem. The Deserializer is expecting an actual string and not an object or an array. Because it is using a JsonMediaTypeFormatter, it won't know how to translate what is being passed to it.
You need to do the following to avoid the null:
public HttpResponseMessage postBlogSearch([FromBody] JToken json){
var jsonResult = JObject.Parse(json.ToString());
var name = jsonResult["responseData"].ToString();
}
For more information see this article.

Categories

Resources