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/
Related
I need to extract json from a particular string which looks like this:
'loglocale=
{
"seed": "pqr",
"pageHashCode": "xxx",
"timestamp": 1553589859880,
"channel": "mobile",
"serviceVersion": "1.0",
"language": "en-CHN"
}
; regStatus=xx; s_dslv=34; s_fid=65-64748; s_vn=64678%26vn%3D1',
groups: undefined ]
I have tried this but could not extract it .
var regex=cookies.match(/{"seed":(\w|\W)*"channel":(\w|\W)*}/);
What is the solution I could use?
Thanks in advance:)
If you know there is only a single plain JSON object like this in the string, you can use this regex to capture the curly braces and everything in between:
const curlyBracesInclusive = /\{([^}]+)\}/
const arr = string.match(curlyBracesInclusive)
// arr[0] will be a the JSON string, if one was found
This is no way guarantees the string is valid JSON. So if you want to run JSON.parse on the result, be aware it will throw an error if the string is invalid.
For the loglocale:
let dataJSON = `
'loglocale=
{
"seed": "pqr",
"pageHashCode": "xxx",
"timestamp": 1553589859880,
"channel": "mobile",
"serviceVersion": "1.0",
"language": "en-CHN"
}
; regStatus=xx; s_dslv=34; s_fid=65-64748; s_vn=64678%26vn%3D1',
groups: undefined ]`
then:
let string = dataJSON.substring(
dataJSON.indexOf("loglocale=") + 10,
dataJSON.lastIndexOf("; regStatus")
)
JSON.parse(string);
Example of given JSON file is as follows:
result = {
"name": "Foo",
"id": "10001",
"values": "1,2,3,4"
};
No, that is not valid JSON.
First, JSON is a string. What you have in the question is a JavaScript object literal expression assigned to the variable result.
Go to https://jsonlint.com/ , paste your file into the box, and click Validate. You will see the following output:
Error: Parse error on line 1:
result = { "name":
^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'
As you can see from the JSON specification , you can't have a variable as a top-level entity. The valid entities in a JSON string are:
a string
an object
an array
a number
Your result variable is not one of those things. It's a variable, which is only valid in JavaScript.
objLiteral = {
"name": "Foo",
"id": "10001",
"values": "1,2,3,4"
};
jsonString = '{ "name": "Foo", "id": "10001", "values": "1,2,3,4" }';
var myObj = JSON.parse( jsonString );
console.log(objLiteral);
console.log(myObj);
console.log(objLiteral.name);
console.log(myObj.name);
<pre>Sample javascript</pre>
I have a "deep" JSON string that I need to pass as GET vars in a URL. It looks like the following:
{
"meta": {
"prune": true,
"returnFields": ["gf", "gh", "gh", "rt"],
"orient": "split"
},
"indicators": [{
"type": "beta",
"computeOn": "gf",
"parameters": {
"timeperiod": 5,
"nbdevup": 2,
"nbdevdn": 2,
"matype": 0
}
}, {
"type": "alpha",
"computeOn": "gf",
"parameters": {
"timeperiod": 30
}
}]
};
When encoding using jQuery.param, the result is as follows:
var recursiveEncoded = jQuery.param(body);
console.log(recursiveEncoded);
meta%5Bprune%5D=true&meta%5BreturnFields%5D%5B%5D=gf&meta%5BreturnFields%5D%5B%5D=gh&meta%5BreturnFields%5D%5B%5D=gh&meta%5BreturnFields%5D%5B%5D=rt&meta%5Borient%5D=split&indicators%5B0%5D%5Btype%5D=beta&indicators%5B0%5D%5BcomputeOn%5D=gf&indicators%5B0%5D%5Bparameters%5D%5Btimeperiod%5D=5&indicators%5B0%5D%5Bparameters%5D%5Bnbdevup%5D=2&indicators%5B0%5D%5Bparameters%5D%5Bnbdevdn%5D=2&indicators%5B0%5D%5Bparameters%5D%5Bmatype%5D=0&indicators%5B1%5D%5Btype%5D=alpha&indicators%5B1%5D%5BcomputeOn%5D=gf&indicators%5B1%5D%5Bparameters%5D%5Btimeperiod%5D=30
Which is decoded to the following:
var recursiveDecoded = decodeURIComponent( jQuery.param(body) );
console.log(recursiveDecoded);
meta[prune]=true&meta[returnFields][]=gf&meta[returnFields][]=gh&meta[returnFields][]=gh&meta[returnFields][]=rt&meta[orient]=split&indicators[0][type]=beta&indicators[0][computeOn]=gf&indicators[0][parameters][timeperiod]=5&indicators[0][parameters][nbdevup]=2&indicators[0][parameters][nbdevdn]=2&indicators[0][parameters][matype]=0&indicators[1][type]=alpha&indicators[1][computeOn]=gf&indicators[1][parameters][timeperiod]=30
If just using a serialized string result on the server leaves the string as the key in a key value pair:
"query": {
"{\"meta\":{\"prune\":true,\"returnFields\":[\"gf\",\"gh\",\"gh\",\"rt\"],\"orient\":\"split\"},\"indicators\":[{\"type\":\"beta\",\"computeOn\":\"gf\",\"parameters\":{\"timeperiod\":5,\"nbdevup\":2,\"nbdevdn\":2,\"matype\":0}},{\"type\":\"alpha\",\"computeOn\":\"gf\",\"parameters\":{\"timeperiod\":30}}]}": ""
},
My backend processing is done with Python. What modules exist to convert the above result to a dict resembling the original object?
Well, since we hashed it out in the comments, I'll post the answer here for posterity.
Use a combination of JSON.stringify on the JavaScript side to serialize your data structure and json.loads on the Python side to deserialize it. Pass the serialized structure as a query string parameter ("query" in your example) and then read the value from that query string parameter in Python. Huzzah!
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
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.
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']