0

I have a python code from which I get an output variable (python list) which i dump into a json file. The resulting json file is this

["Arham", " ", "0.0", " ", "Fayyaz Bhai", " ", "2.48", " ", "Khan sahab", " ", "2.25", " ", "Osama", " ", "0.0", " ", "Yasir (paadri)", " ", "0.0", " "]

Is there any way to parse this .json file (in javascript) ?

Osama
  • 55
  • 1
  • 4
  • Test the validity of the JSON file using a [linter](https://jsonlint.com/) – Krishna Prashatt May 08 '19 at 10:42
  • This file is array of strings. Do you want to convert these array of strings to Json key-value pair model? – Sreehari May 08 '19 at 10:43
  • [MDN entry on JSON](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON) – Matt Ellen May 08 '19 at 10:44
  • Possible duplicate of [Parse JSON in JavaScript?](https://stackoverflow.com/questions/4935632/parse-json-in-javascript) – Klaus D. May 08 '19 at 10:47
  • I can convert them into key value pair model as well . for example [{'name': 'Osama', 'time':0.0},{'name':'Fayyaz bhai','time':'2.48'}] . The thing is that in order to parse a json file the above list has to have a variable name. I.e data = '[{'name': 'Osama', 'time':0.0},{'name':'Fayyaz bhai','time':'2.48'}] ' . I cannot do this python. Is there any way to parse even the above key value pair json ? – Osama May 08 '19 at 11:04
  • You can't edit the python script? It's very easy to make python output a dictionary as JSON. – Matt Ellen May 08 '19 at 11:14
  • Yes. But how are you going to get it there? Are we talking node.js or the browser? – Jared Smith May 08 '19 at 12:01
  • @JaredSmith browser, eventually want to have a website that displays the output of the python code – Osama May 09 '19 at 06:45
  • @MattEllen i can output a dict as a json file. the problem i discovered was that inorder to parse in javascript i needed to have a variable assigned to it . For example the json file is simply {'name':'Osama','age':20} it won't parse this file unless it has a variable and quotations assigned in the following manner , data = '{'name':'Osama','age':20}' – Osama May 09 '19 at 06:47
  • @Osama that is not the case. JSON.parse will work on any valid JSON. e.g. `JSON.parse('{"name":"Osama"}');` will produce an object with a name property set to "Osama"; – Matt Ellen May 09 '19 at 11:15

2 Answers2

0

You can also dump list or dictionary easily into a file using json library.

import json

a = [{'sampleval1': 1, 'sampleval2': 2, 'sampleval3': 3},{'sampleval1': 1, 'sampleval2': 2, 'sampleval3': 3}]
json.dumps(a)
json.dump(a, open('text.json',w), indent=4)
satyam soni
  • 259
  • 1
  • 9
0

If you using nodejs:

let parsed = require('./test.json')
console.log(parsed[0]) // Arham

Just 'require' needed JSON file, and it will be parsed automatically. Arrays are valid JSON so you will get your array of strings.

Xotabu4
  • 3,063
  • 17
  • 29