[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.javascript

convert a string into a json object,

jrough

4/1/2016 2:12:00 AM

It does the first split into a 3 dim arr but it doesn't split those 3 strings up into the data for the jsonObject. Thanks.

<!DOCTYPE html>
<head>
<script>
var string='Janis_SF_WebDev"\n"Debby_SJ_WebDev"\n"Stephanie_Fl_Recruite"\n"';
function doJson(string){
var arr = string.split("\n");
for (i=0;i< 2;i++){
var str= arr[i].split("_");
var jsonObj= {};
jsonObj.name =str[0];
jsonObj.city= str[1];
jsonObj.job = str[2];

}
return jsonObj;
}




var myObj = doJson(string);
console.log(myObj);
</script>
</head>
<body>

</body>

</html>
24 Answers

ram

4/1/2016 2:35:00 AM

0

JRough <janis.rough@gmail.com> writes:
>var string='Janis_SF_WebDev"\n"Debby_SJ_WebDev"\n"Stephanie_Fl_Recruite"\n"';

main = function self()
{ "use strict";
const result = {};
const string = 'Janis_SF_WebDev"\n"Debby_SJ_WebDev"\n"Stephanie_Fl_Recruite"\n"';
const row = string.split( '"\n"' );
for( let i = 0; i < 3; ++i )
{ const record = row[ i ].split( "_" );
const person = {};
person.name = record[ 0 ];
person.city = record[ 1 ];
person.job = record[ 2 ];
result[ i ]= person; }
console.log( JSON.stringify( result ));
return result; };

main();

"{"0":{"name":"Janis","city":"SF","job":"WebDev"},"1":{"name":"Debby","city":"SJ","job":"WebDev"},"2":{"name":"Stephanie","city":"Fl","job":"Recruite"}}"

Stefan Weiss

4/1/2016 8:42:00 AM

0

JRough wrote:
> var string='Janis_SF_WebDev"\n"Debby_SJ_WebDev"\n"Stephanie_Fl_Recruite"\n"';

The line delimiter in this string is '"\n"' instead of '\n' - is that
intentional?

> function doJson(string){
> var arr = string.split("\n");

split() should use the same delimiter as the input: '"\n"'.

> for (i=0;i< 2;i++){

The variable i needs to be declared. And the code is more flexible if
the number of records isn't hard-coded. Speaking of which, the string
contains three records, but you're only counting: zero, one.

> var str= arr[i].split("_");
> var jsonObj= {};
> jsonObj.name =str[0];
> jsonObj.city= str[1];
> jsonObj.job = str[2];

This is ok, but can be writen in a more compact way:

var jsonObj = {
name: str[0],
city: str[1],
job: str[2],
};

> }
> return jsonObj;

This will return the last assembled object. You probably want a list of
all those objects.

> }
>
> var myObj = doJson(string);


You seem to have a misunderstanding about what JSON is: it's a simple
string format for data serialization. What you're building here are
JavaScript objects, not JSON strings.


Here is a version which avoids the mentioned problems:

// I'll assume the line delimiter is actually \n
var string='Janis_SF_WebDev\nDebby_SJ_WebDev\nStephanie_Fl_Recruite\n';

function parseString (string)
{
var lines = string.split("\n");
var result = []; // this array is new, it holds all your objects

for (var i = 0; i < lines.length; i++) {
if (!lines[i].length) {
continue; // skips empty records, like the last one
}
var str = lines[i].split("_");
var obj= {
name: str[0],
city: str[1],
job: str[2],
};
result.push(obj); // add the object to the result
}

return result; // returns the array instead of a single object
}

// this converts the input string into an array of objects
var myList = parseString(string);

// this produces a JSON string from what that list
var json = JSON.stringify(myList);


- stefan

Stefan Weiss

4/1/2016 8:50:00 AM

0

Stefan Ram wrote:
> JRough <janis.rough@gmail.com> writes:
>> var string='Janis_SF_WebDev"\n"Debby_SJ_WebDev"\n"Stephanie_Fl_Recruite"\n"';
>
> main = function self()

Why not just `function main()`?

> { "use strict";
> const result = {};

Why an object instead of an array as container?

> const string = 'Janis_SF_WebDev"\n"Debby_SJ_WebDev"\n"Stephanie_Fl_Recruite"\n"';
> const row = string.split( '"\n"' );
> for( let i = 0; i < 3; ++i )

Hard-coding number of records...

> { const record = row[ i ].split( "_" );
> const person = {};
> person.name = record[ 0 ];
> person.city = record[ 1 ];
> person.job = record[ 2 ];
> result[ i ]= person; }
> console.log( JSON.stringify( result ));
> return result; };
>
> main();
>
> "{"0":{"name":"Janis","city":"SF","job":"WebDev"},"1":{"name":"Debby","city":
>"SJ","job":"WebDev"},"2":{"name":"Stephanie","city":"Fl","job":"Recruite"}}"


Off-topic... does anymody else find it counter-intuitive when most of the
variables are declared as "const"? I've seen this style recently in many
places, and it's technically correct, but for some reason I find it irritating.


- stefan

ram

4/1/2016 4:46:00 PM

0

Stefan Weiss <krewecherl@gmail.com> writes:
>> main = function self()
>Why not just `function main()`?

There was no good reason in this case.

You are right, »function main()« would also
be possible here and it would be shorter.

>>{ "use strict";
>> const result = {};
>Why an object instead of an array as container?

An array is an object too.

You are right insofar that an array would be better style
here, because this object effectively is used as an array.

>>const string = 'Janis_SF_WebDev"\n"Debby_SJ_WebDev"\n"Stephanie_Fl_Recruite"\n"';
>>const row = string.split( '"\n"' );
>>for( let i = 0; i < 3; ++i )
>Hard-coding number of records...

What needs to be hard-coded depends on the specification of
the problem. In the case of this thread, no other
specification than the source code was given. The source
code contained this /fixed/ string constant »'Janis...«.
There also is YAGNI and
c2.com/cgi-bin/wiki?DoTheSimplestThingThatCouldPossiblyWork.

>Off-topic... does anymody else find it counter-intuitive when most of the
>variables are declared as "const"? I've seen this style recently in many
>places, and it's technically correct, but for some reason I find it irritating.

These /are/ constants because they are not assigned to after
their initializations. I deem it most readable to declare
constants with »const« and not with »let«. Because it /is/
a constant, it also should be /declared/ to be a constant.

John Harris

4/1/2016 6:21:00 PM

0

On 1 Apr 2016 16:45:59 GMT, ram@zedat.fu-berlin.de (Stefan Ram) wrote:

>Stefan Weiss <krewecherl@gmail.com> writes:
<snip>
>>Off-topic... does anymody else find it counter-intuitive when most of the
>>variables are declared as "const"? I've seen this style recently in many
>>places, and it's technically correct, but for some reason I find it irritating.
>
> These /are/ constants because they are not assigned to after
> their initializations. I deem it most readable to declare
> constants with »const« and not with »let«. Because it /is/
> a constant, it also should be /declared/ to be a constant.

The code contained
const result = {};
and
result[i]= person;

The constant result is not what I would call a constant. You've
updated it.

John

jrough

4/1/2016 6:32:00 PM

0


I struggled with it and I got this part but the result is obj: webdev??? kind of a weird result but maybe I don't know how to display an object in js.
function doJson(string){
var arr = string.split("\n");
for (i=0;i< 2;i++){
var str= arr[i].split("_");
var jsonObj= {};
jsonObj= { "name": str[0]};
jsonObj= { "city": str[1]};
jsonObj = { "job": str[2]};

}
return jsonObj;
}


the point of the exercise was take a string and make it a json object. I guess the fastest way to do it is fine.



On Thursday, March 31, 2016 at 7:12:31 PM UTC-7, JRough wrote:
> It does the first split into a 3 dim arr but it doesn't split those 3 strings up into the data for the jsonObject. Thanks.
>
> <!DOCTYPE html>
> <head>
> <script>
> var string='Janis_SF_WebDev"\n"Debby_SJ_WebDev"\n"Stephanie_Fl_Recruite"\n"';
> function doJson(string){
> var arr = string.split("\n");
> for (i=0;i< 2;i++){
> var str= arr[i].split("_");
> var jsonObj= {};
> jsonObj.name =str[0];
> jsonObj.city= str[1];
> jsonObj.job = str[2];
>
> }
> return jsonObj;
> }
>
>
>
>
> var myObj = doJson(string);
> console.log(myObj);
> </script>
> </head>
> <body>
>
> </body>
>
> </html>

Aleksandro

4/1/2016 7:22:00 PM

0

On 01/04/16 15:21, John Harris wrote:
> On 1 Apr 2016 16:45:59 GMT, ram@zedat.fu-berlin.de (Stefan Ram) wrote:
>
>> Stefan Weiss <krewecherl@gmail.com> writes:
> <snip>
>>> Off-topic... does anymody else find it counter-intuitive when most of the
>>> variables are declared as "const"? I've seen this style recently in many
>>> places, and it's technically correct, but for some reason I find it irritating.
>>
>> These /are/ constants because they are not assigned to after
>> their initializations. I deem it most readable to declare
>> constants with »const« and not with »let«. Because it /is/
>> a constant, it also should be /declared/ to be a constant.
>
> The code contained
> const result = {};
> and
> result[i]= person;
>
> The constant result is not what I would call a constant. You've
> updated it.

Constant is the object it references, it's address, the pointer,
whatever underlies.

Ben Bacarisse

4/1/2016 7:36:00 PM

0

John Harris <niam@jghnorth.org.uk.invalid> writes:

> On 1 Apr 2016 16:45:59 GMT, ram@zedat.fu-berlin.de (Stefan Ram) wrote:
>
>>Stefan Weiss <krewecherl@gmail.com> writes:
> <snip>
>>>Off-topic... does anymody else find it counter-intuitive when most of the
>>>variables are declared as "const"? I've seen this style recently in many
>>>places, and it's technically correct, but for some reason I find it irritating.
>>
>> These /are/ constants because they are not assigned to after
>> their initializations. I deem it most readable to declare
>> constants with »const« and not with »let«. Because it /is/
>> a constant, it also should be /declared/ to be a constant.
>
> The code contained
> const result = {};
> and
> result[i]= person;
>
> The constant result is not what I would call a constant. You've
> updated it.

const makes the binding immutable, the object isn't.

--
Ben.

Stefan Weiss

4/1/2016 10:51:00 PM

0

JRough wrote:
> I struggled with it and I got this part but the result is obj: webdev???
> kind of a weird result but maybe I don't know how to display an object in js.
[...]
> var jsonObj= {};
> jsonObj= { "name": str[0]};
> jsonObj= { "city": str[1]};
> jsonObj = { "job": str[2]};

You assign {} to jsonObj, and then you assign three other things to it. This
cannot possibly work. Please read Stefan Ram's and my reply and try to work
our suggestions into your code.


- stefan

Stefan Weiss

4/1/2016 11:19:00 PM

0

Stefan Ram wrote:
> Stefan Weiss <krewecherl@gmail.com> writes:
>>> for( let i = 0; i < 3; ++i )
>> Hard-coding number of records...
>
> What needs to be hard-coded depends on the specification of
> the problem. In the case of this thread, no other
> specification than the source code was given. The source
> code contained this /fixed/ string constant »'Janis...«.
> There also is YAGNI and
> c2.com/cgi-bin/wiki?DoTheSimplestThingThatCouldPossiblyWork.

YAGNI is my secret Achilles heel :/
I'm always trying to read between the lines and anticipate the actual
requirements instead of what was explicitly asked. I've written and deleted
thousands of lines of code for this reason.

>> Off-topic... does anymody else find it counter-intuitive when most of the
>> variables are declared as "const"? I've seen this style recently in many
>> places, and it's technically correct, but for some reason I find it irritating.
>
> These /are/ constants because they are not assigned to after
> their initializations. I deem it most readable to declare
> constants with »const« and not with »let«. Because it /is/
> a constant, it also should be /declared/ to be a constant.

I know, they are technically constants.
But the semantics seem off to me... I can't really explain this properly. In
other languages, I would use `const` or `#define` (etc) to indicate a value
that will be used literally throughout the rest of the program. Any
reference to the constant can be replaced by its value. Declaring a `const`
only for the duration of a single loop iteration just doesn't seem "right".


- stefan