Am trying to parse this string using JSON.parse.
Ex.
str = "{'xyz': ['300543979001'], 'abc': ['1193'], 'serial_no': ['1'], 'product_tax_amt': ['408.813'], 'product_mrp': ['4699.0'], 'product_qty': ['1.0'], 'contract_type': ['FG'], 'product_tax_rate': ['14.5'], 'is_vat_exclusive': ['True'], 'product_net_amt': ['3228.213'], 'sap_details': [''], 'reference_invoice_no': [''], 'pd': [\"1||9911143976001||18373205-L-I-F-T- RACER WN'S, PINK, 5||11143976||PUMA-18373205-L-I-F-T- RACER WN'S, PINK, 5-5||4699.0||291||629||1||2||41\"], 'topup_offers': ['{}'], 'product_discount_percentage': ['40.0'], 'total_discount_percentage': ['40.0'], 'basic_tax_rate': ['0.0'], 'total_discount_amt': ['1879.6'], 'product_return_qty': ['0.0'], 'product_gross_amt': ['0.0'], 'invoice_no': ['11065011391'], 'product_discount_amt': ['1879.6'], 'is_voided': ['False'], 'supplier_no': ['198'], 'addl_tax_rate': ['0.0'], 'product_cost_amt': ['1.0'], 'code': ['4046643889059']}"
Note:: This is in single quoted & few values might contains quotes also, like [\"1||9911143976001||18373205-L-I-F-T- RACER WN'S, PINK, 5||11143976||PUMA-18373205-L-I-F-T- RACER WN'S, PINK, 5-5||4699.0||291||629||1||2||41\"]
>> JSON.parse(str)
But its throwing error: Unexpected token '
EDITED
I tried few here and there things to replace these single quotes with double quotes,
>> str = str.replace(/'/g, '"')
>> JSON.parse(str)
But then it raises error,
SyntaxError: Unexpected token S
Is there any way using regex or something, so i could parse that string?
One of your fields has single quotes in it:
9911143976001||18373205-L-I-F-T- RACER WN'S, PINK, 5||11143976**strong text**
Try removing them, or escaping them.
Ok, here's the point: if that's data from the server, that's a terrible data format. It's not valid JSON and it has poor string escaping. In your case, you would want to change single quotes with doubles, as many already suggested, but you have horrible fields like this:
[\"1||9911143976001||18373205-L-I-F-T- RACER WN'S, PINK, 5||11143976||PUMA-18373205-L-I-F-T- RACER WN'S, PINK, 5-5||4699.0||291||629||1||2||41\"]
Now, the ideal solution would be to fix the 's with some kind of regular expression, but:
1) I couldn't for the life of me figure out a working one;
2) I'm starting to think it's not actually possible to catch every possibility.
I hope someone will correct me if I'm wrong about this. Anyway, if this is actually the case, I think the easiest way is the most discouraged one: the dreadful eval(). That thing may not be valid JSON, but it is (surprisingly) a correct JS object definition.
eval("var data = " + str);
If you need a JSON string, you could use stringify():
var json = JSON.stringify(data);
Here is a working fiddle.
I have to say this in advance: suggesting eval() is a terrible move on this website, and rightly so. But before downvoting please consider that we have a pathological data format from the server, and no easy way to fix it before processing. And I will say it again: if somebody can come up with a working regular expression for replacing an arbitrary number of single quotes within double quotes that will certainly be a far better way to go.
EDIT:
If you are sure that the only problematic field is the pd one, you could use that information to simply replace all single quotes in that particular field. That would be much safer.
JSON strings are delimited with double quote " characters. You are using single quote characters, which is legal in JavaScript literals, but not in JSON.
It is useful to use a tool such as JSON Lint (which would have picked up this error) to test your JSON when you craft it by hand. (Usually you should use a well-tested library function to generate your JSON).
Your JSON is wrong, according to json.org:
An array is an ordered collection of values...
And
A value can be a string in double quotes, or a number, or true or false or null, or an object or an array.
So you must wrap your strings in double quotes instead of single quotes.
Edit:
A valid JSON would be:
{
"xyz": [
"300543979001"
],
"abc": [
"1193"
],
"serial_no": [
"1"
],
"product_tax_amt": [
"408.813"
],
"product_mrp": [
"4699.0"
],
"product_qty": [
"1.0"
],
"contract_type": [
"FG"
],
"product_tax_rate": [
"14.5"
],
"is_vat_exclusive": [
"True"
],
"product_net_amt": [
"3228.213"
],
"sap_details": [
""
],
"reference_invoice_no": [
""
],
"pd": [
"1||9911143976001||18373205-L-I-F-T- RACER WN'S",
"PINK",
"5||11143976||PUMA-18373205-L-I-F-T- RACER WN'S",
"PINK",
"5-5||4699.0||291||629||1||2||41"
],
"topup_offers": [
"{}"
],
"product_discount_percentage": [
"40.0"
],
"total_discount_percentage": [
"40.0"
],
"basic_tax_rate": [
"0.0"
],
"total_discount_amt": [
"1879.6"
],
"product_return_qty": [
"0.0"
],
"product_gross_amt": [
"0.0"
],
"invoice_no": [
"11065011391"
],
"product_discount_amt": [
"1879.6"
],
"is_voided": [
"False"
],
"supplier_no": [
"198"
],
"addl_tax_rate": [
"0.0"
],
"product_cost_amt": [
"1.0"
],
"code": [
"4046643889059"
]
}
And here is a JSBin Demo.
PS: I'm not sure if there should be "s in first and last elements of pd array. If so just add \"s to these values.
Using single Quotes (' ') is badpractice-- U better use Double Quotes (" ") for Literals.
For Example:
var str = '{ "foo": "bar" }';
var json = JSON.parse(str);
json['foo']
Related
I'm retrieving hashmap data from an api into my react app. the data looks like this..
[
[
"d243dc7-6fe8-151b-4ca8-1be528f2b36",
"[\"Jonny\",70]"
],
[
"8affa17-76d1-13e-6380-7cd2a3e3647",
"[\"Lucy\",106,"pic3.jpg"]"
],
[
"841cb28-24c7-872-3c66-63253800c8d",
"[\"Mike\",0]"
],
[
"6128e-182-cfb4-708b-c40a3ba2e6e",
"[\"Elodie\",23,"me.jpg"]"
],
[
"e55ef4c-8d41-3be4-27d-aae53330584",
"[\"Jacob\",9,"img-004.jpeg"]"
]
]
I need to render this data into a table.
Using map and with with data.slice(0, 1) I've managed to pull out the key (the long string), but I need help separating the name, number and optional image. I tried experimenting with various operators. I thought this would work
{data.slice(1, 2).toString().substring(2,data.slice(1, 2).length-2)}
but it just returns ["
I'm hoping there is a simpler way to do it!
You presented the data in a strange format, but this works:
const data = [
[
"d243dc7-6fe8-151b-4ca8-1be528f2b36",
"[\"Jonny\",70]"
],
[
"8affa17-76d1-13e-6380-7cd2a3e3647",
"[\"Lucy\",106,\"pic3.jpg\"]"
],
[
"841cb28-24c7-872-3c66-63253800c8d",
"[\"Mike\",0]"
],
[
"6128e-182-cfb4-708b-c40a3ba2e6e",
"[\"Elodie\",23,\"me.jpg\"]"
],
[
"e55ef4c-8d41-3be4-27d-aae53330584",
"[\"Jacob\",9,\"img-004.jpeg\"]"
]
];
const data1 = JSON.parse(data.slice(1, 2)[0][1]);
console.log('name', data1[0]);
console.log('numb', data1[1]);
console.log('file', data1[2]);
{data.slice(1, 2).toString().substring(2,data.slice(1, 2).length-2)}
^ ^^^^^^^^^^^^^^^^
In the string "["Jonny",70]" , you only want to skip the first character "[", so your first parameter of substring() should be index 1
you forgot to transfer data.slice(1, 2) to string, so it's still an array and its length would be 1
so your code should be revised to:
data.slice(1, 2).toString().substring(1, data.slice(1, 2).toString().length - 2)
CSV file data
"Name", "OfcLocation", "IPAddress", "Port" ,"Role"
"Tom", "USA", "XX.XXX.X.XX", "4300", "Admin"
"Mark", "Spain", "XX.XXX.X.XX", "4080", "Limited"
"Jack", "Japan", "XX.XXX.X.XX", "9200", "Admin"
I am reading the CSV file. I use npm package ngx-parser for reading csv file. After reading csv file it's return data as the following format.
const response:any[];
[""Name"", ""OfcLocation"", ""IPAddress"", ""Port"" ,""Role""],
[""Tom"", ""USA"", ""XX.XXX.X.XX"", ""4300"", ""Admin"" ]
[ ""Mark"", ""Spain"", ""XX.XXX.X.XX"", ""4080"", ""Limited"" ]
[ ""Jack"", ""Japan"", ""XX.XXX.X.XX"", ""9200"", ""Admin"" ]
I tried to replace two double quotes with single quotes through
let jData = JSON.stringify(response).replace(/""/g,'"');
and again try to convert into JSON
let parseData = JSON.parse(jData);
getting error as Uncaught SyntaxError: Unexpected token \ in JSON.
Basically, I want data like this, after replace two double quotes with single quote
["Name", "OfcLocation", "IPAddress", "Port" ,"Role"],
["Tom", "USA", "XX.XXX.X.XX", "4300", "Admin" ]
[ "Mark", "Spain", "XX.XXX.X.XX", "4080", "Limited" ]
[ "Jack", "Japan", "XX.XXX.X.XX", "9200", "Admin" ]
I am Changing My Answer First U have to Stringify ur response and then u have to replace that string like this..
if stringify not working then change response to string like this
let string= `${your response data here}`
and then replace
let string = `[""Name"", ""OfcLocation"", ""IPAddress"", ""Port"" ,""Role""],[""Tom"", ""USA"", ""XX.XXX.X.XX"", ""4300"", ""Admin"" ][ ""Mark"", ""Spain"", ""XX.XXX.X.XX"", ""4080"", ""Limited"" ][ ""Jack"", ""Japan"", ""XX.XXX.X.XX"", ""9200"", ""Admin"" ]`
let myString = string.replace(/""/g, '"');
console.log(myString)
When you get your response back as stringified json those quotes will be backslashed like this:
"[{\"Name\":\"OfcLocation\",\"IPAddress\":\"Port\"}]"
Are you saying that when you get your results back they look like this?
Which would seem odd.
"[{\"\"Name\"\":\"\"OfcLocation\"\",\"\"IPAddress\"\":\"\"Port\"\"}]"
Ok it might help to use a backslash before your quote like this.
response.replace(/\"\"/g,'"');
If that doesn't work then test your stringify method that it is indeed returning a valid string.
You can try validating your json here:
https://jsonlint.com/
I've got a problem with my node.js application.
I'm trying to parse string using JSON.parse like this:
try{
skills = JSON.parse(user.skills);
}catch(e){
console.log(e);
}
In user.skills I've got such a string:
"[ { name: Dreamweaver, level: 60 }, { name: Phototshop, level: 80 }]"
and it throws me: [SyntaxError: Unexpected token n].
Can anybody help me?
Thanks in advance :)
Your JSON data is incorrect. There should be quotes "" around strings.
should be like this
var str = "[ { \"name\": \"Dreamweaver\", \"level\": 60 }, { \"name\": \"Phototshop\", \"level\": 80 }]"
If you want to see how should be a proper JSON String Try this
var data = {name:"mark"}
JSON.stringify(data) //returns "{"name":"mark"}" Here you have to care about escaping quotes.
JSON data needs identifiers and values to be strings, try this:
'[ { "name": "Dreamweaver", "level": "60" }, { "name": "Phototshop", "level": "80" }]';
You can use http://jsonlint.com/ to varify json. After that we can stringify and parse json respectively.
HI I am trying to create a JSON file in which I want to store some data for different files. The problem is I cannot figure the correct syntax. Here is what I have so far:
var object = {
"id-1" :[
{
"type":"Corporate Website",
"tech":"HTML" ,"CSS" , "Javascript/jQuery"
}
],
"id-2" :[
]
}
I seem to be getting an error at "tech".If that is not corect how can I enumarate multiple elements?I am sorry for the noob question I have been using javascript for a short period of time and I am still very confused with the language.
{
"id-1": [
{
"type": "Corporate Website",
"tech": [
"HTML",
"CSS",
"Javascript/jQuery"
]
}
],
"id-2": []
}
Note the array like syntax for "tech".
Tech should be an array (enclosed in square brackets):
"tech": ["HTML", "CSS", "Javascript/jQuery"]
Source:
An array is an ordered collection of values. An array begins with [
(left bracket) and ends with ] (right bracket). Values are separated
by , (comma).
http://www.json.org/
I'm writing some functions that construct what should be a properly formatted JSON string which I can then parse into a JSON object.
My object is failing on JSONLint with the following error:
syntax error, unexpected TINVALID at line 2
[
SERVER: {
ip = 10.10.10.1,
port = 8100
},
TYPES: [
ssh,
shht
]
]
I assumed that this would give me an array of JavaScript objects.
Even if I did this instead (object instead of array):
{
SERVER: {
ip = 10.10.10.1,
port = 8100
},
TYPES: [
ssh,
shht
]
}
It doesn't work and I get the same error:
I assume that with the object, I would be able to access some data like so:
var serverIP = myObject.SERVER.ip;
That's certainly what I'd like to do.
Many thanks in advance,
Joe
You have to use quotation marks around the identifiers, and the values that are strings:
This is valid JSON:
{
"SERVER": {
"ip": "10.10.10.1",
"port": 8100
},
"TYPES": [
"ssh",
"shht"
]
}
If you are actually not using JSON at all, but just trying to create a Javascript literal object, then you should not use JSONLint to check the code.
This is valid Javascript:
var myObject = {
SERVER: {
ip: '10.10.10.1',
port: 8100
},
TYPES: [
'ssh',
'shht'
]
};
This validates:
{
"SERVER": {
"ip" : "10.10.10.1",
"port" : 8100
},
"TYPES": [
"ssh",
"shht"
]
}
you need double quotes around every string and since its an object you need : instead of =
your mixing json object with javascript arrays
this is json format
{
"item":"value",
"item2":"value"
}
and this would be a JavaScript array
[
"apple",
"orange"
]
os I think this is what you are looking for
{
"SERVER": {
"ip": "10.10.10.1",
"port": 8100
},
"TYPES": [
"ssh",
"shht"
]
};