Angular.js format json data - javascript

"[{rest_id:"2", cate_id:"4", rest_name:"Samraat Curry Hut", adress:"6275 Jarvis Ave, Newark, CA 94560", city:"Newark", state:"New Jersey", country:"US", email_id:"", rest_url:"Samraat-Curry-Hut", phone_no:"(510) 745-7000", rest_image:"http://www.mealhi5.com/images/restaurant/Samraat-Curry-Hut.jpg"}]"
top array my result but my required bottom array add double quote key
rest_id to "rest_id" all key add double quote("")
my required array
This Angular JS
first JSON is my input and output second array
[{"rest_id":"2", "cate_id":"4", "rest_name":"Samraat Curry Hut", "adress":"6275 Jarvis Ave, Newark, CA 94560", "city":"Newark", "state":"New Jersey", "country":"US", "email_id":"", "rest_url":"Samraat-Curry-Hut", "phone_no":"(510) 745-7000", "rest_image":"http://www.mealhi5.com/images/restaurant/Samraat-Curry-Hut.jpg"}]

Take a look at JSON.parse (if you want to use it as a JSON object)
var foo = JSON.parse("[{rest_id:"2", ...}]");

You can do one thing use regular expressing in that case:-
var a= JSON.stringify([{"rest_id":"2", "cate_id":"4", "rest_name":"Samraat Curry Hut", "adress":"6275 Jarvis Ave, Newark, CA 94560", "city":"Newark", "state":"New Jersey", "country":"US", "email_id":"", "rest_url":"Samraat-Curry-Hut", "phone_no":"(510) 745-7000", "rest_image":"http://www.mealhi5.com/images/restaurant/Samraat-Curry-Hut.jpg"}]);
a=a.replace(/"(\w+)"\s*:/g, '$1:');
Fiddle

Related

How to loop through parsed JSON array using jquery .each()

I have the following data which is being parsed and then I am looping through to attempt to get each state ID and name.
{
"billing": {
"ACT": "Australian Capital Territory",
"NSW": "New South Wales",
"NT": "Northern Territory",
"QLD": "Queensland",
"SA": "South Australia",
"TAS": "Tasmania",
"VIC": "Victoria",
"WA": "Western Australia"
},
"shipping": {
"ACT": "Australian Capital Territory",
"NSW": "New South Wales",
"NT": "Northern Territory",
"QLD": "Queensland",
"SA": "South Australia",
"TAS": "Tasmania",
"VIC": "Victoria",
"WA": "Western Australia"
}
}
data = '{"billing":{"ACT":"Australian Capital Territory","NSW":"New South Wales","NT":"Northern Territory","QLD":"Queensland","SA":"South Australia","TAS":"Tasmania","VIC":"Victoria","WA":"Western Australia"},"shipping":{"ACT":"Australian Capital Territory","NSW":"New South Wales","NT":"Northern Territory","QLD":"Queensland","SA":"South Australia","TAS":"Tasmania","VIC":"Victoria","WA":"Western Australia"}}';
data = jQuery.parseJSON( data );
billingData = data.billing;
$(billingData).each( function( key, value ) {
console.log( key + value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I am expecting the console to loop through each state ID and the label, but I get they key as 0 and the value as an object, I have also tried looping through the outputted object (contained in value from the original .each).
I have also tried looping through billingData[0].
You need to use jQuery.each() instead of .each() to do this work.
The .each() loop through jquery elements but jQuery.each() loop through array or object.
data = '{"billing":{"ACT":"Australian Capital Territory","NSW":"New South Wales","NT":"Northern Territory","QLD":"Queensland","SA":"South Australia","TAS":"Tasmania","VIC":"Victoria","WA":"Western Australia"},"shipping":{"ACT":"Australian Capital Territory","NSW":"New South Wales","NT":"Northern Territory","QLD":"Queensland","SA":"South Australia","TAS":"Tasmania","VIC":"Victoria","WA":"Western Australia"}}';
data = jQuery.parseJSON(data);
billingData = data.billing;
$.each(billingData, function(key, value) {
console.log(key +": "+ value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
billingData is not an array. It's an object. jQuery each will let you iterate through an object as though it were an array, or you could just use object methods:
data = '{"billing":{"ACT":"Australian Capital Territory","NSW":"New South Wales","NT":"Northern Territory","QLD":"Queensland","SA":"South Australia","TAS":"Tasmania","VIC":"Victoria","WA":"Western Australia"},"shipping":{"ACT":"Australian Capital Territory","NSW":"New South Wales","NT":"Northern Territory","QLD":"Queensland","SA":"South Australia","TAS":"Tasmania","VIC":"Victoria","WA":"Western Australia"}}';
data = jQuery.parseJSON(data);
billingData = data.billing;
Object.keys(billingData).forEach(function(key) {
console.log(key + ": " + billingData[key])
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
There are two types of each:
$.each(array, function( key, value ) {
});
$('.element').each(function () {
});

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);

How to convert this array of strings to array object

I ma having this string returned from my C# code. I need to implement Google Maps. How d i convert this into array.
String
var array = [["Andover - Wyevale Garden Centre","Concession A","Andover Garden Centre","Salisbury Road","Andover","SP11 7DN","01264 710114","14.9 miles","51.1998552","-1.5111393"],
["Portsmouth - Gunwharf Quays","Unit 29","Gunwharf Quays","Portsmouth","Hampshire","PO1 3TZ","02392 819558","20.8 miles","50.7963663","-1.1065603"],
["Chichester","83 North Street","Chichester","West Sussex","PO19 1LQ","01243 380058","25.9 miles","50.837269","-0.77846"],
["Newport - Isle of Wight","117/119 High Street","Newport","Isle of Wight","PO30 1TP","01983 527485","27.1 miles","50.700399","-1.294872"],
["Guildford","20-21 North Street","Guildford","Surrey","GU1 4AF","01483 456978","29.8 miles","51.2369881","-0.5731617"]]
i dont know but when i do array[1][0] it should return "Portsmouth" in chrome console BUT it is coming as undefined.
I suspect array variable is identified as string and not array.
when i do array[0][4] i get "A" as output.
Please help
use this .. this will running on my side .
var array = '[["d","ddd","sadasd","Salisbury Road","Andover","SP11 7DN","01264 710114","14.9 miles","51.1998552","-1.5111393"],["Portsmouth - Gunwharf Quays","Unit 29","Gunwharf Quays","Portsmouth","Hampshire","PO1 3TZ","02392 819558","20.8 miles","50.7963663","-1.1065603"],["Chichester","83 North Street","Chichester","West Sussex","PO19 1LQ","01243 380058","25.9 miles","50.837269","-0.77846"],["Newport - Isle of Wight","117/119 High Street","Newport","Isle of Wight","PO30 1TP","01983 527485","27.1 miles","50.700399","-1.294872"],["Guildford","20-21 North Street","Guildford","Surrey","GU1 4AF","01483 456978","29.8 miles","51.2369881","-0.5731617"]]'
var arrayObj = JSON.parse(array)
console.log(arrayObj)
console.log(arrayObj[1][0])
// returns---
Portsmouth - Gunwharf Quays
OK try this:
var array = [["Andover - Wyevale Garden Centre","Concession A","Andover Garden Centre","Salisbury Road","Andover","SP11 7DN","01264 710114","14.9 miles","51.1998552","-1.5111393"],
["Portsmouth - Gunwharf Quays","Unit 29","Gunwharf Quays","Portsmouth","Hampshire","PO1 3TZ","02392 819558","20.8 miles","50.7963663","-1.1065603"],
["Chichester","83 North Street","Chichester","West Sussex","PO19 1LQ","01243 380058","25.9 miles","50.837269","-0.77846"],
["Newport - Isle of Wight","117/119 High Street","Newport","Isle of Wight","PO30 1TP","01983 527485","27.1 miles","50.700399","-1.294872"],
["Guildford","20-21 North Street","Guildford","Surrey","GU1 4AF","01483 456978","29.8 miles","51.2369881","-0.5731617"]];
Try removing your encompassing double quotes and include a terminating semi-colon ;...
var array = [["Andover - Wyevale Garden Centre","Concession A","Andover Garden Centre","Salisbury Road","Andover","SP11 7DN","01264 710114","14.9 miles","51.1998552","-1.5111393"],
["Portsmouth - Gunwharf Quays","Unit 29","Gunwharf Quays","Portsmouth","Hampshire","PO1 3TZ","02392 819558","20.8 miles","50.7963663","-1.1065603"],
["Chichester","83 North Street","Chichester","West Sussex","PO19 1LQ","01243 380058","25.9 miles","50.837269","-0.77846"],
["Newport - Isle of Wight","117/119 High Street","Newport","Isle of Wight","PO30 1TP","01983 527485","27.1 miles","50.700399","-1.294872"],
["Guildford","20-21 North Street","Guildford","Surrey","GU1 4AF","01483 456978","29.8 miles","51.2369881","-0.5731617"]];

JavaScript find names in strings

What's a good JavaScript library for searching a given string for a large list of names.
For example, given a list of 1000 politicians names find every instance in a string and wrap it in a span.
Priorities are performance with a growing list of names, and accuracy in determining difference between eg, "Tony Blair", "Tony Blair III".
For example, this:
["Tony Blair", "Margaret Thatcher", "Tony Blairite", "Tony Blair III", etc...]
"The best PM after Tony Blair was Margaret Thatcher."
Becomes:
"The best PM after <span class="mp">Tony Blair</span> was <span class="mp">Margaret Thatcher</span>."
var names = ['foo','bar'];
var content = "this foo is bar foobar foo ";
for (var c=0,l=names.length;c<l;c++) {
var r = new RegExp("\\b("+names[c]+")\\b","gi");
content = content.replace(r,'<span class="mp">$1</span>');
}

Categories

Resources