How can I extract a json from a string in javascript - 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);

Related

How To Add A String Inside An Object For The Given Example

Hi iam finding the best way to add a string inside the given object.Any help would be appreciated
my String is 'created'
Down Below Is My Data
{
"id": "222",
"list": [
{
"name": "Tony",
}
],
iam trying to insert 'created' in the data like this
{
"id": "222",
"list": [
{
"name": "Tony",
"type":"created"
}
]
The string you've provided looks a lot like JSON data. You can convert a JSON string to an actual javascript object by using the JSON.parse(string) method.
With this object we then can query it's list property - which in your case is an array of objects - and add a new property type to each of the arrays elements. The final step is converting the object back to a JSON string using the JSON.stringify(object) method.
Here's an example:
let str = `{
"id": "222",
"list": [
{
"name": "Tony"
}
]
}`;
let data = JSON.parse(str);
data.list.forEach(element => {
element.type = "created";
});
str = JSON.stringify(data);
console.log(str);
const myObj = {
"id": "222",
"list": [
{
"name": "Tony",
}
],
};
myObj.list[0].type = "created";
This is the way you can do this. But you'd better use secified index of list items;
const index = 0; // Or any other way to get this
myObj.list[index].type = "created";

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

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>

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.

How to write proper string to work with JSON.parse

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.

Extract value between HTML-tags using JavaScript

How can I extract the value between the tags (49% in message) using Javascript?
I will first parse the JSON with JSON.parse.
{
"id": "189180337778229046",
"from": {
"name": "My FB page",
"category": "Automobiles and parts",
"id": "189180337778229046"
},
"subject": "A good deal",
"message": "<p><strong>49%</strong></p><p>This is a good deal for you.</p>",
"icon": "http://static.ak.fbcdn.net/rsrc.php/v1/yY/r/d1gBp2bDGEuh.gif",
"created_time": "2011-11-02T10:49:56+0000",
"updated_time": "2011-11-02T10:49:56+0000"
}
A simple RegExp will do. Assume obj to hold the value of the parsed JSON string:
var percent = obj.message.match(/<strong>(.*?)<\/strong>/i)[1]; //Returns 49%
Easiest will be to use jQuery which looks like you're already using: (as JSON.parse is part of it)
var myValue = $(data.message).find("strong").eq(0).text();
You can do :
var pattern = /([0-9]+%)/gi;
var result = obj.message.match(pattern);
This will only match integer numbers though..

Categories