Can valid JSON file consist of only one single object's description? - javascript

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>

Related

Javascript replace two double quotes with single double quotes of Array

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/

Convert an array in string format to javascript array

I have an array which is in string format,
var str = {
id: 123,
changes: "[[atr:test1, old:null, new:null], [atr:messageText, old:test here, new:hello test], [atr:status, old:null, new:1]]"
}
var d = str.changes
I tried to convert the 'changes' array from string format using different methods by combining split(), replace(), slice() etc...and even JSON.parse(), but nothing worked.
Is there any way to convert this into javascript array?
Note that the string is not valid anything but string.
It is not a valid array, and the string is not valid JSON.
If you can, get the server to change it to the valid JSON string
"[{\"atr\":\"test1\", \"old\":null, \"new\":null}, {\"atr\":\"messageText\", \"old\":\"test here\", \"new\":\"hello test\"}, {\"atr\":\"status\", \"old\":null, \"new\":1}]"
If the response is ALWAYS on the format you gave, then you can create valid JSON
var str = {
id: 123,
changes: "[[atr:test1, old:null, new:null], [atr:messageText, old:test here, new:hello test], [atr:status, old:null, new:1]]"
}
// change the inner [ ] to { }
let changes = str.changes.replace(/\[\[/g, "[{").replace(/\], \[/g, "},{").replace(/\]\]/g, "}]")
// change the unquoted keys and values to quoted keys and values
changes = changes.replace(/(\w+):/g, '"$1":').replace(/:([\w ]+)([},])/g, ':"$1"$2')
// parse the object
changes = JSON.parse(changes);
// replace "null" with null - could have been done above bt the regex would be nasty
changes.forEach(item => Object.keys(item).forEach(key => item[key] = item[key] === "null" ? null : item[key]))
console.log(changes)
I think the problem is that the key 'changes' do not any valid JSON. You can validate, format it here.
If there is a valid JSON in 'changes' key, It can be converted to Js array using JSON.parse();, Something like:
var str = { id: 123,
changes: `[
[
{
"atr": "test1",
"old": null,
"new": null
}
],
[
{
"atr": "messageText",
"old": "test here",
"new": "hello test"
}
],
[
{
"atr": "status",
"old": null,
"new": 1
}
]
]`
}
var d = JSON.parse(str.changes);
console.log(d);
//str.changes Object:
[[[object Object] {
atr: "test1",
new: null,
old: null
}], [[object Object] {
atr: "messageText",
new: "hello test",
old: "test here"
}], [[object Object] {
atr: "status",
new: 1,
old: null
}]]

How can I extract a json from a string in javascript

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

Parse decodeURIComponent JSON string with Python

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

json stringify failing when value is without double quotes

When I try to convert below json to string, getting unexpected desired output when the value is not surrounded with double quotes:
JSON data:
[
{
"Name": "param1",
"Type": "Integer",
"Default Value": 8778
},
{
"Name": "param2",
"Type": "Float",
"Default Value": 1.4
},
{
"Name": "param3",
"Type": "String",
"Default Value": true
},
{
"Name": "param4",
"Type": "String",
"Default Value": "test"
}
]
Current result:
[{"Name":"param1","Type":"Integer","Default Value":8778}, {"Name":"param2","Type":"Float","Default Value":**1.4**}, {"Name":"param3","Type":"String","Default Value":**true**}, {"Name":"param4","Type":"String","Default Value":**"test"**}]
Expected result:
[{"Name":"param1","Type":"Integer","Default Value":**"8778"**}, {"Name":"param2","Type":"Float","Default Value":**"1.4"**}, {"Name":"param3","Type":"String","Default Value":**"true"**}, {"Name":"param4","Type":"String","Default Value":**"test"**}]
I tried below code: but it is not working.
jsondata = JSON.stringify(confTableData);
jsondata = jsondata.replace(/:(\d+|\d*\.\d+)([,\}])/g, ':"$1"$2'); // only Integer & Float type values replaced
jsondata = jsondata.replace(/:(.)([,\}])/g, ':"$1"$2'); It gives strange result.
Can anyone help me on the regex pattern to match my requirement.
The JSON spec outlines what you're seeing as standard behavior and I'd recommend that you operate on the number as a number instead of a string.
If you need to modify this for some reason, you can use a "replacer" function as shown in the JSON.stringify spec.
var numbersAsStringsJSON = JSON.stringify(myData, replacer);
function replacer(key, value) {
if (typeof value === "number") { return String(value); }
else { return value; }
}
See JSFiddle for working example.
Numbers do not need to be wrapped in double quotes. Check out some of the examples on json.org.
If you want the numbers to be strings in JSON, you can make them strings before you stringify your object, e.g.:
var data = {
"Name": "param1",
"Type": "Integer",
"Default Value": 8778
};
data["Default Value"] = String(data["Default Value"]);
var json = JSON.stringify(data);
If you do it before you stringify the JSON you won't need to run a regex over it.

Categories