String into array (nodejs) [duplicate] - javascript

This question already has answers here:
Convert string array representation back to an array
(3 answers)
Closed 5 years ago.
I have a string of integers
str = "[7,2,7,7,2,7,7,4,3,2]"
and i want to get an array so that i can manipulate the data easily, but i have no idea how to do it. Can you help me ? I'm sure it's a basic task but i am not very familiar with node.
Thank you.

Try JSON.parse(yourStr). Alternately:
yourString.substr(1,arr.length-2).split(",").map((el) => {
return parseInt(el)
})

Looks like JSON, parse it with JSON.parse
numbers = JSON.parse("[7,2,7,7,2,7,7,4,3,2]")

Related

Javascript Take JSON string convert to array [duplicate]

This question already has answers here:
How can I convert a comma-separated string to an array?
(19 answers)
Closed 3 years ago.
*****No JQUERY*****
I have a string passed into my Javascript that looks like below. I want to convert it into an array.
I have
{"test":"1,180,35"}
I want
an array where index 0 = 1, index 1 = 180, index 2 = 35.
How would I achieve this?
Parse the string, pull out the property value for property test, split it on ,.
var input = '{"test":"1,180,35"}'
var jsObj = JSON.parse(input);
var arr = jsObj.test.split(",");
console.log(arr);
use JSON.parse() to convert a string into a json object.
But, you are looking to parse a series of numbers into an array, so what you really want is split(",")
Use the JSON object
let arr = JSON.parse('{"test":"1,180,35"}').test.split(',');
For example:
var yourData = `{"test":"1,180,35"}`
JSON.parse(yourData).split(',')

Creating dictionary using python from javascript var data [duplicate]

This question already has answers here:
Convert [key1,val1,key2,val2] to a dict?
(12 answers)
Make dictionary from list with python [duplicate]
(5 answers)
Convert list into a dictionary [duplicate]
(4 answers)
Closed 4 years ago.
trying to figure out how to do this and have yet to find a good solution. I pulled this data out of an XML response. It was in a var tag. Now what I would like to do is create a dictionary out of it. The domain.com should be paired with the number right listed behind it.
This is the data:
[
'cb131.domain1.com', '147827',
'cb143.domain2.com', '147825',
'cb175.domain1.com', '147454',
'cb190.domain.com', '146210',
'cb201.domain.com', '146208',
'cb219.domain.com', '146042',
'cb225.domain.com', '146282',
'cb900.domain.com', '148461',
'cb901.domain.com', '148493',
'cb902.domain.com', '148495',
'cb903.domain.com', '148497',
'cb904.domain.com','148499',
'cb905.domain.com', '148501',
'cb906.domain.com', '148503',
'cb907.domain.com', '148505',
'cb908.domain.com', '148507',
'cb909.domain.com', '148509'
]
So for example cb131.domain1.com should be paired with 147827, cb143.domain2.com paired with 147825 and so on.
Drawing a blank on a good quick solution on how to do this. Hopefully someone can help.
Thanks!
Edited with answer I choose below:
I choose this answer and also to help anyone else I add a nice way to print out the results (data is the string I obtained):
import ast
i = iter(ast.literal_eval(data))
dic = dict(zip(i, i))
for key , value in dic.items():
print(key, " :: ", value)
This should do it. Assuming the list is saved to a variable l:
keys = l[::2]
vals = l[1::2]
dic = dict(zip(keys, vals))
You can create an iterator from the list after using ast.literal_eval to parse it from the input text, zip the iterator with itself, and pass the generated sequence of tuples to the dict constructor:
import ast
i = iter(ast.literal_eval(data))
dict(zip(i, i))
Assuming you have the above in a python array called data, you can do:
new_data = []
for i in range(0, len(data), 2):
new_data.append((data[i], data[i+1]))
Now new_data would be a list of tuples. You could certainly create a better data structure to hold these pairs if you want.
I do not yet know Python that I can write a snippet, but:
initialize an empty dictionary in Python
create a for loop counting index from 0 to length of your array in steps of two.
inside add a dictionary entry with key of value at index and value at index + 1
perhaps check for duplicates
Does this answer help you?
This is Python - quickly google'd:
dictionary = { }
for idx in range(0, len(data), 2)
dictionary[data[idx]] = data[idx + 1]

Javascript long integer from server is not accurate [duplicate]

This question already has answers here:
Javascript - convert an EXTRA LARGE Number to string in JSON before the default parsing
(4 answers)
Closed 4 years ago.
I've got an API which I make a get request to fetch data. When i try to save the Id, I see Javascript round the last digit of it and it makes my program to break!
I see THIS QUESTION but how can I save each Id as string?
I'm using a global array to store the selected items' data so, anyway to save one attribute of a JSON in string?
I'm going to have (for example) 3 items and make another get request for each Id:
axios.get(`http://api.nemov.org/api/v1/Market/Symbol/${this.props.ID}`)
One of those Ids, is: 9481703061634967 but JS convert that to 9481703061634968 so the get request is broken!
Any solution?
See my solution on this question:
Transform the response to string, then apply a repalce with a regex to
convert Id field to string type:
const axios = require("axios");
axios.get(url, {transformResponse: [data => data]}).then((response) => {
let parsed = JSON.parse(response.data.replace(/"Id":(\d+),/g, '"Id":"$1",'))
console.log(parsed)
});
Use this:
let strId = this.props.ID.toString();
axios.get(`http://api.nemov.org/api/v1/Market/Symbol/${strId}`)

Get data from JS array of objects [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 4 years ago.
Probably very easy question, but I couldn't find solution.
How to get data from this object?
That how it looks in consolo.log()
UPDATE:
Thank you for you answers.
That what I used before and it worked, but when I try on this array it returns error.
console.log(array[1].data);
Output picture
UPDATE2:
So I tried to make it a text, but I couldn't.
console.log(tempArray);
console.log("String: " + tempArray.toString());
console.log("Stringify: " + JSON.stringify(tempArray));
Here is output:
Stringify attempt result
Maybe there is something wrong with how I create this array.
let tempArray = [];
And in the loop
tempArray.push({"id": id, "data": data.routes[0].geometry});
Thank you,
Dmitry
That's an array of objects, so you would get elements from it like so:
console.log(obj[i].data)
Where i is the element (numbered 0 through 2) that you want to access.

Convert string to javascript array in MVC [duplicate]

This question already has answers here:
How do I write unencoded Json to my View using Razor?
(3 answers)
Closed 7 years ago.
I have ViewBag.Result with string value "[['Garreth','VP'],['Johan','IT'],['Test','QA']]"
I want to convert it as javascript array
var dataset =
[
['Garreth','VP'],
['Johan','IT'],
['Test','QA']
]
Obviously var dataset = '#ViewBag.Result' doesn't work because javascript treat is as string but not array. Any idea how to do this?
Thanks
Just remove the single quotes:
var dataset = #ViewBag.Result

Categories